【问题标题】:Big files download through php function readfile not working通过php函数readfile下载大文件不起作用
【发布时间】:2013-12-19 20:59:14
【问题描述】:

我有一段代码可以在许多服务器上运行良好。 用于通过readfile php函数下载文件。

但在一台特定的服务器上,它不适用于大于 25mb 的文件。

代码如下:

        $sysfile = '/var/www/html/myfile';
        if(file_exists($sysfile)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="mytitle"');
            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($sysfile));
            ob_clean();
            flush();
            readfile($sysfile);
            exit();

当我尝试下载小于25mb的文件时没有问题,当文件较大时,下载的文件为0字节。

我已尝试使用函数 read() 和 file_get_contents,但问题仍然存在。

我的php版本是5.5.3,内存限制设置为80MB。 错误报告已打开,但即使在日志文件中也没有显示错误。

【问题讨论】:

  • 首先通过 PHP 传递这些文件的原因是什么?
  • 抱歉 80mo 是 80MB(兆字节)
  • 在这段代码之前我检查了访问权限并且不希望用户直接访问文件

标签: php apache file-io download


【解决方案1】:

感谢 witzawitz 的回答,这是完整的解决方案:

我需要使用 ob_end_flush() 和 fread();

<?php 
$sysfile = '/var/www/html/myfile';
    if(file_exists($sysfile)) {
   header('Content-Description: File Transfer');
   header('Content-Type: application/octet-stream');
   header('Content-Disposition: attachment; filename="mytitle"');
   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($sysfile));
   ob_clean();
   ob_end_flush();
   $handle = fopen($sysfile, "rb");
   while (!feof($handle)) {
     echo fread($handle, 1000);
   }
}
?>

【讨论】:

    【解决方案2】:

    我最近遇到了同样的问题。我已经尝试过不同的标题和其他。 适合我的解决方案。

    header("Content-Disposition: attachment; filename=export.zip");
    header("Content-Length: " . filesize($file));
    ob_clean();
    ob_end_flush();
    readfile($file);
    

    所以尝试将 flush 更改为 ob_end_flush。

    【讨论】:

    • 它不适合我 :( 我有同样的结果。
    • 这是解决方案的一部分;)我需要使用 fead 而不是 readfile
    猜你喜欢
    • 2018-04-16
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2012-07-31
    相关资源
    最近更新 更多