chinazaike
chinazaike

Reputation: 517

proper way of downloading large files in php

Am using this code to download files of about 5mb and is working great.

Now when I use it to download files of about 10g and above. it will either freeze the browser or causes memory issue. I think the best way will be to read the files in bytes. something like the code below.

$chunk = 1 * 1024 * 1024 // 1m 
while (!feof($stream)) {
fwrite(fread($stream, $chunk));
}

My questions is please what is the best way. can someone help me with the integration of above code with the one below. Any possible solution will be appreciated. Thanks

Here is the working code for small file download

$output_filename = 'output10g.zip';
$host = "http://localhost/test/10g_file.zip"; //source 

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
echo $result = curl_exec($ch);
curl_close($ch);
$stream = fopen("download/$output_filename", 'wb');
fwrite($stream, $result);
fclose($stream);

Upvotes: 0

Views: 184

Answers (1)

N'Bayramberdiyev
N'Bayramberdiyev

Reputation: 3620

I recommend using fopen() and fread() for handling large files.

$download_file = 'movie.mp4';

$chunk = 1024; // 1024 kb/s

if (file_exists($download_file) && is_file($download_file)) {
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . filesize($download_file));
    header('Content-Disposition: filename=' . $download_file);

    $file = fopen($download_file, 'r');

    while(!feof($file)) {
        print fread($file, round($chunk * 1024));
        flush();
    }

    fclose($file);
}

Tested on 2.5GB of MPEG-4 file.

Do not forget to set max_execution_time = 0 in your php.ini file.

Upvotes: 0

Related Questions