2
votes

I'm trying to download a large file using PHP and CURL. If you open a link the following code should initiate the download.

$download = $downloadFolder.$result['file'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $download);
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$output = curl_exec($ch);
curl_close($ch);

header('Content-Description: File Transfer');
header("Content-Type: video/mp4");
header("Content-Disposition: attachment; filename=".str_replace(" ", "_", $result['file']));
header("Content-Length: " . strlen($output));
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Connection: close');

echo $output;
exit;

It works fine with smaller files (e.g. 35MB), but on large ones I get the following PHP Error:

Allowed memory size of 134217728 bytes exhausted (tried to allocate 63981406 bytes) in /var/www/typo3conf/ext/...

The memory_limit in the php.ini is already set to 128MB but it's still not working. Do I need so set this value even higher?

1

1 Answers

4
votes

By default cURL is keeping response in memory, so if you got bigger file to download you can hit the ceiling. The solution is to tell cURL to write server data to file directly:

<?php
if ($fh = fopen('file.tmp', 'wb+')) {

    curl_setopt($ch, CURLOPT_URL, $download);
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
    curl_setopt($ch, CURLOPT_TIMEOUT, 300);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // tell it you want response written to file
    curl_setopt($ch, CURLOPT_FILE, $fh); 

    curl_exec($ch); 
    curl_close($ch);

    fclose($fh);

    ... output the file you just downloaded ...
}