How Seek How Seek - 1 month ago 20
PHP Question

How to download big files in PHP

I use this code to download/read files from a server.

header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Content-type: application/file");
header('Content-length: '.filesize($file_to_download));
header('Content-disposition: attachment; filename='.basename($file_to_download));
readfile($file_to_download);
exit;


it's working fine to download files but when the file is big it's showing an error "File not found, problem file loading". Please tell me what I could change on this code for big file downloads.

Answer

Try like this:

 $chunkSize = 1024 * 1024;
    $fd = fopen($file_to_download, 'rb');
    while (!feof($fd)) {

        $buffer = fread($fd, $chunkSize);
        echo $buffer;
        ob_flush();

        flush();
    }
    fclose($fd);