Big files download through php function readfile not working

不打扰是莪最后的温柔 提交于 2020-02-01 05:21:12

问题


I have a piece of code that works well on many servers. It is used to download a file through the readfile php function.

But in one particular server it does not work for files bigger than 25mb.

Here is the code :

        $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();

When I try to download a file lower than 25mb there is no problem, when the file is bigger, the file downloaded is 0 bytes.

I've tried with the function read() and file_get_contents but the problem still present.

My php version is 5.5.3, memory limit is set to 80MB. Error reporting is on but there is no error displayed even in log file.


回答1:


Here is the complete solution thanks to the answer of witzawitz:

I needed to use ob_end_flush() and 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:


I've the same problem recently. I've experimented with different headers and other. The solution that works for me.

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

So try to change flush to ob_end_flush.



来源:https://stackoverflow.com/questions/20691567/big-files-download-through-php-function-readfile-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!