Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP readfile() and large downloads

Tags:

php

download

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.

like image 536
Nirmal Avatar asked Jun 01 '10 01:06

Nirmal


People also ask

How to download large files using PHP?

php function readfile_chunked($filename,$retbytes=true) { $chunksize = 1*(1024*1024); // how many bytes per chunk the user wishes to read $buffer = ''; $cnt =0; $handle = fopen($filename, 'rb'); if ($handle === false) { return false; } while (!

What is the use of Readfile ()?

The ReadFile function returns when one of the following conditions occur: The number of bytes requested is read. A write operation completes on the write end of the pipe. An asynchronous handle is being used and the read is occurring asynchronously.

How to read large file in PHP?

Read a file: We will read the file by using fopen() function. This function is used to read and open a file. Syntax: fopen("filename", access_mode);


1 Answers

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.

like image 161
m1tk4 Avatar answered Sep 23 '22 02:09

m1tk4