barin
barin

Reputation: 4651

How to return a file in 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?

Upvotes: 40

Views: 80714

Answers (4)

Gabriel Spiteri
Gabriel Spiteri

Reputation: 4978

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.");
        } 

Upvotes: 106

DarkDust
DarkDust

Reputation: 92316

If the file is publicly accessable, just do a simple redirect to the URL of your file.

Upvotes: 2

Evert
Evert

Reputation: 99523

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.

Upvotes: 3

Adam Byrtek
Adam Byrtek

Reputation: 12202

If the file is public, then you can just serve it as a static file directly from the web server (e.g. Apache), and make download.php redirect to the static URL. Otherwise, you have to use readfile to send the file to the browser after authenticating the user (remember about the Content-Dispositon header).

Upvotes: 1

Related Questions