How to read a Base64 string as a file, on server side, without saving it in web server, directly by PHP?

1k views Asked by At

Many days ago, I have posted a question on StackOverflow, and Jaime has answered it for me, at here.


header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename= ".$file."");
echo base64_decode($file);

But, I don't want to download these file from database, I want to get it in web browser only.

For example, when I browse to my PHP page (http://example.com/save.php?fileid=23413), the web browser will read these ouput files as a local files in your computer, exactly:

  1. If the output file is: JPG, PNG, GIF,... MP3, MP4,..., TXT, HTML... It can be handled and played in web browser.
  2. If other output file type, such as: EXE, DLL, JAR... It must be downloaded by web browser
  3. Saving files with file extensions is not neccessary.
  4. Don't decode Base64 strings to files by web browser (data:[<mediatype>][;base64],<data>).

How can I output data stream to browser and have the browser handle it the same as a real file on the server, instead of always downloading?


I have read other questions on StackOverflow about Base64, but there is no question similar to my question. Please read my question carefully to understand the differences between my question and other questions.

1

There are 1 answers

0
Anthony On

To get the mime-type from the data stream and set it to the header, use the built in finfo class, like:

$filecontents = base64_decode($file);

$finfo = new finfo(FILEINFO_MIME);
$file_mimetype = $finfo->buffer($filecontents);    

header("Content-type: $file_mimetype");
header("Content-disposition: inline; filename=$filename");
echo $filecontents;