0

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

5
  • 2
    Well it's print base64_decode('02FAF....'); and not workable if that file is larger than the memory available to your PHP interpreter. Commented Mar 29, 2012 at 9:04
  • Mario, post this usegul answer not as a comment but an answer itself :) Commented Mar 29, 2012 at 9:07
  • @mario Thank you, What if the file is large, is there any way to stream it? Commented Mar 29, 2012 at 9:11
  • Yes. Store the binary data in a separate file then. Commented Mar 29, 2012 at 9:12
  • It's clear now, Thank you very much @mario Commented Mar 29, 2012 at 9:19

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
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-Encoding
0

Perhaps this example can help you http://www.php.net/manual/en/function.base64-encode.php#105200

Regards!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.