PHP download script for big files

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...

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

2

Leave a Reply

*

*


  • Aly
    21 August 2012 at 13:45

    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.

  • Mark
    11 September 2012 at 10:50

    I was using ob_clean() – which didn’t work, changed it to ob_end_clean and I’m in business.

    Thanks for this!