0

Below is the code I am using to stream a non-web facing file to a browser for download. The file received is a match on the number of bytes however when I do a CRC check of the file, it's different. Any ideas on where I am going wrong?

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.filesize($dir));
flush();

$file = fopen($dir, "r");
$size = filesize($dir);

while (!feof($file))
{
    if ($size > 1048576)
    {
        print fread($file, 1048576);
        $size = $size - 1048576;
    }
    else
    {
        print fread($file, $size);
    }
    flush();
}

fclose($file);
exit;
  • 1
    Whats the reason for the code which limits the file size? And why not just use readFile() – ADyson May 06 '22 at 07:44
  • When using readfile() the file never completes and chrome says file incomplete. The files can be 1gb+ in size. – Pete OConnell May 06 '22 at 08:36
  • In that case PHP is probably running out of memory I'd guess. Any server error logs when that happens? – ADyson May 06 '22 at 08:38
  • @ADyson this is exactly the problem - I'd rather not be bumping up the memory to multiple GBs, any ideas on a way around this? – Pete OConnell May 06 '22 at 08:59
  • 1
    readfile should not cause problems per se with these kind of file sizes, it has been optimized over the years to be able to handle this. Do you perhaps have output buffering active? That can have a negative impact, in that case you should flush the buffer & turn further buffering off, see https://stackoverflow.com/a/11795311/1427878 – CBroe May 06 '22 at 09:04

0 Answers0