PHP,文件下载

我正在使用简单的文件下载脚本:

if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } 

它正在我的本地服务器高达200MB。

当我在我的网站尝试这个代码时,下载173KB而不是200MB的文件。

我检查了一切,写了一些自定义代码(使用ob函数和fread而不是readfile),但不能下载大文件。

谢谢你的回答。

  • 我使用的是Apache 2.2,PHP 5.3
  • 所有处理大文件的PHP设置都可以。 (执行时间,内存限制,…

我在下面的代码中遇到的一个问题是,你无法控制输出stream,让PHP在不知道背景中到底发生了什么的情况下处理它。

你应该做的是build立一个输出系统,你可以控制和复制accros服务器。

例如:

 if (file_exists($file)) { if (FALSE!== ($handler = fopen($file, 'r'))) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: chunked'); //changed to chunked header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); //header('Content-Length: ' . filesize($file)); //Remove //Send the content in chunks while(false !== ($chunk = fread($handler,4096))) { echo $chunk; } } exit; } echo "<h1>Content error</h1><p>The file does not exist!</p>"; 

这只是基本的,但要一试!

也请阅读我的答复在这里: file_get_contents => PHP致命错误:允许的内存用尽

看来readfile可能有长文件的问题。 正如@Khez所问,可能是脚本运行太久了。 一个快速的谷歌search导致了几个分块文件的例子。

http://teddy.fr/blog/how-serve-big-files-through-php http://www.php.net/manual/en/function.readfile.php#99406

对于某些场景的一个解决scheme是,你可以使用PHP脚本来智能地决定从哪里下载文件,而不是直接从PHP发送文件,你可以返回一个redirect到客户端,然后包含被处理的直接链接由Web服务器单独。

这至less可以通过两种方式完成:PHP脚本将文件复制到“下载区”中,例如可以通过其他背景/服务脚本定期清除“旧”文件,或者将真正的永久位置客户。

每个解决scheme的情况当然都有缺点。 在这一个是根据客户端(curl,wget,GUI浏览器)请求文件,他们可能不支持redirect你在另一个,这些文件是非常暴露于外部世界,并可以在任何时候都读取没有PHP脚本的(访问)控制。

你确定你的脚本可以运行足够长的时间,并有足够的内存吗?

你真的需要输出缓冲吗?

真正的解决scheme是避免使用PHP脚本仅仅发送文件到客户端,这是过度的,你的web服务器更适合于任务。

大概你有一个通过PHP发送文件的理由,也许用户必须先validation身份? 如果是这种情况,那么你应该在lighttpd上使用X-Accel-Redirect (如果你使用的是nginx)或X-Sendfile (以前是X-LIGHTTPD-send-file)。

如果您使用的是Apache,我发现了一些对mod_xsendfile的引用,但是我从来没有亲自使用它,如果您pipe理主机,我怀疑它是否已经安装。

如果这些解决scheme是站不住脚的,我真的需要更多关于实际问题的信息:为什么你首先通过PHP发送这些文件?