Nirmal
Nirmal

Reputation: 9549

PHP readfile() and large downloads

While setting up an online file management system, and now I have hit a block.

I am trying to push the file to the client using this modified version of readfile:

function readfile_chunked($filename,$retbytes=true) { 
   $chunksize = 1*(1024*1024); // how many bytes per chunk 
   $buffer = ''; 
   $cnt =0; 
   // $handle = fopen($filename, 'rb'); 
   $handle = fopen($filename, 'rb'); 
   if ($handle === false) { 
       return false; 
   } 
   while (!feof($handle)) { 
       $buffer = fread($handle, $chunksize); 
       echo $buffer; 
       ob_flush(); 
       flush(); 
       if ($retbytes) { 
           $cnt += strlen($buffer); 
       } 
   } 
       $status = fclose($handle); 
   if ($retbytes && $status) { 
       return $cnt; // return num. bytes delivered like readfile() does. 
   } 
   return $status; 
}

But when I try to download a 13 MB file, it's just breaking at 4 MB. What would be the issue here? It's definitely not the time limit of any kind because I am working on a local network and speed is not an issue.

The memory limit in PHP is set to 300 MB.

Thank you for any help.

Upvotes: 5

Views: 5881

Answers (2)

Andreas Linden
Andreas Linden

Reputation: 12721

do NOT flush your output but try to buffer it and then send it to teh client in one piece.

ob_clean(); // in case anything else was buffered
ob_start();

// do read/echo operations

ob_end_flush();

Upvotes: 1

m1tk4
m1tk4

Reputation: 3467

Most likely you are hitting the response buffer limit set by your webserver. IIS and FastCGI are known to have 4mb as the default buffer size. I would start your search with looking into the webserver<->PHP SAPI configuration.

Upvotes: 4

Related Questions