如何在 PHP 中返回文件

php
2022-08-30 13:32:01

我有一个文件

/file.zip

用户来到

/download.php

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


答案 1

我想你想要这个:

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

答案 2

readfile 将完成这项工作,并将流直接传递回 Web 服务器。这不是最好的解决方案,因为文件发送时,PHP仍然运行。为了获得更好的结果,您需要像X-SendFile这样的东西,大多数Web服务器都支持X-SendFile(如果您安装了正确的模块)。

一般来说(如果你关心重负载),最好把一个代理Web服务器放在你的主应用程序服务器前面。这将更快地释放您的应用程序服务器(例如apache),并且代理服务器(Varnish,Squid)往往更擅长将字节传输到具有高延迟的客户端或通常较慢的客户端。


推荐