Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP output file on disk to browser

Tags:

I want to serve an existing file to the browser in PHP. I've seen examples about image/jpeg but that function seems to save a file to disk and you have to create a right sized image object first (or I just don't understand it :))

In asp.net I do it by reading the file in a byte array and then call context.Response.BinaryWrite(bytearray), so I'm looking for something similar in PHP.

Michel

like image 238
Michel Avatar asked Jan 08 '10 16:01

Michel


People also ask

How can I see the output of a PHP file?

With PHP, there are two basic ways to get output: echo and print . In this tutorial we use echo or print in almost every example. So, this chapter contains a little more info about those two output statements.

What is PHP Readfile function?

The readfile() function in PHP is an inbuilt function which is used to read a file and write it to the output buffer. The filename is sent as a parameter to the readfile() function and it returns the number of bytes read on success, or FALSE and an error on failure.

Can PHP read from file?

So here are the steps required to read a file with PHP. Open a file using fopen() function. Get the file's length using filesize() function. Read the file's content using fread() function.

What is the use of File_get_contents in PHP?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.


2 Answers

There is fpassthru() that should do exactly what you need. See the manual entry to read about the following example:

<?php  // open the file in a binary mode $name = './img/ok.png'; $fp = fopen($name, 'rb');  // send the right headers header("Content-Type: image/png"); header("Content-Length: " . filesize($name));  // dump the picture and stop the script fpassthru($fp); exit;  ?> 

See here for all of PHP's filesystem functions.

If it's a binary file you want to offer for download, you probably also want to send the right headers so the "Save as.." dialog pops up. See the 1st answer to this question for a good example on what headers to send.

like image 104
Pekka Avatar answered Sep 29 '22 19:09

Pekka


I use this

  if (file_exists($file)) {           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, post-check=0, pre-check=0');         header('Pragma: public');         header('Content-Length: ' . filesize($file));          ob_clean();         flush();         readfile($file);         exit;      }  
like image 32
Knase Avatar answered Sep 29 '22 20:09

Knase