Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big files download through php function readfile not working

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.

like image 877
Jiwoks Avatar asked Dec 25 '22 16:12

Jiwoks


2 Answers

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);
   }
}
?>
like image 188
Jiwoks Avatar answered Feb 20 '23 09:02

Jiwoks


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.

like image 45
witzawitz Avatar answered Feb 20 '23 10:02

witzawitz