PHP函数readfile无法下载大文件。

4

我有一段代码在许多服务器上表现良好。

它用于通过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传递的原因是什么? - Pekka
抱歉,80mo指的是80MB(兆字节)。 - Jiwoks
在这段代码之前,我检查了访问权限,不希望用户直接访问文件。 - Jiwoks
2个回答

7

感谢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);
   }
}
?>

6

最近我也遇到了同样的问题。我尝试了不同的头文件和其他方法,但是对我有用的解决方案是:

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

尝试将flush更改为ob_end_flush


对我来说不起作用 :( 我得到了相同的结果。 - Jiwoks
这是解决方案的一部分 ;) 我需要使用fead而不是readfile - Jiwoks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接