Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a file in PHP

Tags:

php

I have a file

/file.zip

A user comes to

/download.php

I want the user's browser to start downloading the file. How do i do that? Does readfile open the file on server, which seems like an unnecessary thing to do. Is there a way to return the file without opening it on the server?

like image 315
barin Avatar asked May 30 '11 11:05

barin


People also ask

How do I return a PHP file?

The return keyword ends a function and, optionally, uses the result of an expression as the return value of the function. If return is used outside of a function, it stops PHP code in the file from running.

How can I get content of a file 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.

What does the return function do in PHP?

The purpose of return statement in PHP is to return control of program execution back to the environment from which it was called. Upon returning, execution of expression following the one which invooked other function or module.

How do I get the PHP file from a website?

Use the basename() function to return the file basename if the file path is provided as a parameter. Save the file to the given location.


2 Answers

I think you want this:

        $attachment_location = $_SERVER["DOCUMENT_ROOT"] . "/file.zip";
        if (file_exists($attachment_location)) {

            header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
            header("Cache-Control: public"); // needed for internet explorer
            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: Binary");
            header("Content-Length:".filesize($attachment_location));
            header("Content-Disposition: attachment; filename=file.zip");
            readfile($attachment_location);
            die();        
        } else {
            die("Error: File not found.");
        } 
like image 140
Gabriel Spiteri Avatar answered Oct 07 '22 15:10

Gabriel Spiteri


readfile will do the job OK and pass the stream straight back to the webserver. It's not the best solution as for the time the file is sent, PHP still runs. For better results you'll need something like X-SendFile, which is supported on most webservers (if you install the correct modules).

In general (if you care about heavy load), it's best to put a proxying webserver in front of your main application server. This will free up your application server (for instance apache) up quicker, and proxy servers (Varnish, Squid) tend to be much better at transfering bytes to clients with high latency or clients that are generally slow.

like image 2
Evert Avatar answered Oct 07 '22 15:10

Evert