Home » Php » header – Download Large File with PHP readfile(); Downloading is stopping around 890mb

header – Download Large File with PHP readfile(); Downloading is stopping around 890mb

Posted by: admin February 25, 2020 Leave a comment

Questions:

I write some small script and it is working ok! however when i try download large file such a more than 1GB Download is stopping around ~880MB

Am i doing something wrong? or is there any better solution for download big file with PHP

This is my code

<?php

set_time_limit(0);
ini_set('memory_limit', '5000M');

//This File is 4GB size
$url = 'example.com/files/file_name.zip';

$headers = get_headers($url, TRUE); //collectind header information from file Url

$filesize = $headers['Content-Length']; //File size

while (ob_get_level()) ob_end_clean();
header('Content-Type: application/zip');
header('Content-Disposition: filename=' . basename($url));
header('Content-length: ' . $filesize);
header('Cache-Control: no-cache');
header("Content-Transfer-Encoding: chunked");
ob_flush();
flush();
readfile($url);
exit;

How to&Answers:

I suspect that you’re hitting a memory limit error. Normally readfile avoids using much memory, but depending on your settings it can consume RAM in the process. Check your error logs to confirm that you’re seeing a memory allocation error, and if you are seeing it, try getting rid of the while and ob_flush and flush and just add something like this after the headers:

if (ob_get_level()) {
    ob_end_clean();
}

readfile($url);

Also, don’t pump your memory limit up to 5GB… if this is working correctly you shouldn’t require hardly any memory.

If that’s not it, can you confirm that you’re serving a remotely hosted ZIP file (i.e. you don’t have direct access to the ZIP file on the current server)?