通过php函数readfile下载大文件不起作用

Jiw*_*oks 4 php apache file-io download

我有一段在许多服务器上运行良好的代码。它用于通过 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();
Run Code Online (Sandbox Code Playgroud)

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

我已经尝试过函数 read() 和 file_get_contents 但问题仍然存在。

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

wit*_*itz 6

我最近也有同样的问题。我尝试过不同的标题和其他。对我有用的解决方案。

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

因此尝试将flush更改为ob_end_flush


Jiw*_*oks 6

由于 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);
   }
}
?>
Run Code Online (Sandbox Code Playgroud)