如何在PHP中返回文件

bar*_*rin 24 php

我有一个文件

/file.zip
Run Code Online (Sandbox Code Playgroud)

用户来了

/download.php
Run Code Online (Sandbox Code Playgroud)

我希望用户的浏览器开始下载文件.我怎么做?readfile是否在服务器上打开文件,这似乎是不必要的事情.有没有办法在不在服务器上打开文件的情况下返回文件?

Gab*_*eri 72

我想你想要这个:)

        $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.");
        } 
Run Code Online (Sandbox Code Playgroud)

HTH :)

  • 仅供参考:[使用HTTP标头"Cache-Control:public"会有什么风险?](http://stackoverflow.com/q/3339859/216084) (3认同)
  • 您可以只使用 ```header("Content-Type: application/octet-stream");``` 来使其适用于所有文件类型,而不仅仅是 ```.zip```。 (2认同)