Big files download through php function readfile n

2020-07-17 05:59发布

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.

2条回答
成全新的幸福
2楼-- · 2020-07-17 06:22

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);
   }
}
?>
查看更多
放我归山
3楼-- · 2020-07-17 06:31

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.

查看更多
登录 后发表回答