How to download large files through PHP script?


To download large files through PHP script, the code is as follows −

Example

<?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 (!feof($handle)) {
      $buffer = fread($handle, $chunksize);
      echo $buffer;
      if ($retbytes) {
         $cnt += strlen($buffer);
      }
   }
   $status = fclose($handle);
   if ($retbytes && $status) {
      return $cnt; // return number of bytes delivered like readfile() does.
   }
   return $status;
}
?>

Output

This will produce the following output −

The large file will be downloaded.

The function ‘readfile_chunked’ (user defined) takes in two parameters- the name of the file and the default value of ‘true’ for the number of bytes returned meaning that large files have been successfully downloaded. The variable ‘chunksize’ has been declared with the number of bytes per chunk that needs to be read. The ‘buffer’ variable is assigned to null and the ‘cnt’ is set to 0. The file is opened in binary read mode and assigned the variable ‘handle’ .

Until the end of file of the ‘handle’ is reached, the while loop runs and reads the contents of the file based on the number of chunks that need to be read. Next it is displayed on the screen. If the value of ‘retbytes’ (the second parameter to the function) is true, the length of the buffer is added to the ‘cnt’ variable. Otherwise, the file is closed and the ‘cnt’ value is returned. In the end, the function returns the ‘status’.

Updated on: 09-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements