php 如何在PHP中返回文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6175533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return a file in PHP
提问by barin
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?
我希望用户的浏览器开始下载文件。我怎么做?readfile 是否在服务器上打开文件,这似乎是不必要的事情。有没有办法在不打开服务器的情况下返回文件?
回答by Gabriel Spiteri
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.");
}
回答by Adam Byrtek
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).
如果文件是公开的,那么您可以直接从 Web 服务器(例如 Apache)将其作为静态文件提供,并使 download.php 重定向到静态 URL。否则,您必须在对用户进行身份验证后使用 readfile 将文件发送到浏览器(请记住Content-Dispositon
标头)。
回答by Evert
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).
readfile 将完成这项工作并将流直接传回网络服务器。这不是发送文件的最佳解决方案,PHP 仍在运行。为了获得更好的结果,您需要像 X-SendFile 这样的东西,大多数网络服务器都支持它(如果您安装了正确的模块)。
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.
通常(如果您关心重负载),最好在主应用程序服务器前面放置一个代理网络服务器。这将更快地释放您的应用程序服务器(例如 apache),并且代理服务器(Varnish、Squid)往往更擅长将字节传输到具有高延迟的客户端或通常较慢的客户端。