PHP download script for big files

Total
0
Shares

Today i had a task at one customer where a directory of files needed to be downloaded using a PHP script. For one strange reason the script failed and the browser displayed a File not found error. I couldn’t for a while figure out what was happening. But after some test it was obvious that the file size was too big for the server (90 MB)  because with a smaller file size it worked.

So this was the original code:

 

header("Content-length:".filesize($filename));
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="downloadpackage.zip"');
header('Content-Transfer-Encoding: binary');
readfile($filename);
exit();

After some digging i quickly found the solution,  it is :  ob_end_clean();

Here is the final code:

header("Content-length:".filesize($filename));
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="downloadpackage.zip"');
header('Content-Transfer-Encoding: binary');
ob_end_clean();
readfile($filename);
exit();

Works like a charm with any file size

3 comments
  1. Thanks so much for this solution, confirming it works for me as well. Had been using a very similar script and with files sized around 200MB the server would drop the file in random places along the transfer, sometimes 90MB sometimes 120MB or wherever but never complete the download.

    Had thought it was a PHP script timeout issue but increasing max_execution_time = xxx in the php.ini file or inside the script set_time_limit(0) made no difference.

  2. I’ve spent a lot of time researching this era, to find it to be something so simple to fix is amazing. I’m downloading 170mb files now, Thank you Laszlo…

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like