Search code examples
phpdownloadoutput-bufferinghttp-compression

php: how to properly serve file download using readfile with output buffering compression


I have following code (from http://www.php.net/manual/en/function.readfile.php):

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

But it does not works if i have ob_start('ob_gzhandler'); before header() statement.


Solution

  • Use this code (you do not need to modify ob_start('ob_gzhandler'); if you have it before):

    error_reporting(0); //Errors may corrupt download
    ob_start(); //Insert this
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    //header('Content-Length: ' . filesize($file)); //Content now is compressed, you need to disable this
    //Note: Download also works if you do not comment out Content-Lenght (tested in IE8)
    ob_clean();   
    ob_end_flush(); //Modify flush() to ob_end_flush();
    readfile($file); 
    exit;