使用curl下载大文件时发生致命错误


Fatal Error when downloading a large file with curl

我正在尝试使用PHP和CURL下载一个大文件。如果您打开一个链接,下面的代码应该会启动下载。

$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;

它适用于较小的文件(例如35MB),但对于较大的文件,我会得到以下PHP错误:

允许的内存大小134217728字节已用尽(尝试分配63981406字节),位于/var/www/typeo3conf/ext/。。。

php.ini中的memory_limit已经设置为128MB,但它仍然不起作用。是否需要将此值设置得更高?

默认情况下,cURL会将响应保存在内存中,因此如果您有更大的文件要下载,则可能会达到上限。解决方案是告诉cURL将服务器数据直接写入文件:

<?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 ...
}