How to return a file in PHP

前端 未结 4 1136
别跟我提以往
别跟我提以往 2020-11-28 07:41

I have a file

/file.zip

A user comes to

/download.php

I want the user\'s browser to start downloading the

相关标签:
4条回答
  • 2020-11-28 08:01

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

    0 讨论(0)
  • 2020-11-28 08:03

    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.

    0 讨论(0)
  • 2020-11-28 08:23

    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.");
            } 
    
    0 讨论(0)
  • 2020-11-28 08:25

    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).

    0 讨论(0)
提交回复
热议问题