I want to encode binary file into base64 and put it into php page (inline with the code), And when request that page it streams the file to the browser,popup a download dialog.
Any ideas
2 Answers
Seems pretty straightforward. As with readfile, use http headers to force download, and then echo the encoded string.
$decoded_data = base64_decode($encoded_data);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($decoded_data);
ob_clean();
flush();
echo $decoded_data;
exit;
3 Comments
DaveRandom
I won't downvote you for this immediately, but if you don't fix it I might... You have decoded the string twice, once to get the length of the data and once to output it. You should store the result of
base64_decode() in variable, and pass the variable to strlen() and echo - what if the data was 100MB?Juhani
Good point. I still wouldn't recommend this for big files, because the whole file is loaded into memory, but at least this way it's only decoded once.
DaveRandom
I personally wouldn't recommend it at all, there is almost no reason to do this. I admit it's potentially nice to make a whole application contained within one file (which is the only legitimate reason I can think of for doing this) but the small aesthetic gain vs the large performance cost makes it not really viable. But your answer is good, if a little over engineered - The caching headers would be better set towards client caching, since the string is static in the script and there is a large overhead in serving the file, and FYI there is no such HTTP header as
Content-Transfer-EncodingPerhaps this example can help you http://www.php.net/manual/en/function.base64-encode.php#105200
Regards!
print base64_decode('02FAF....');and not workable if that file is larger than the memory available to your PHP interpreter.