使用curl下载大文件时出现致命错误

时间:2016-05-12 07:37:01

标签: php 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错误:

  

在/ var / www / typo3conf / ext /...

中,允许的内存大小为134217728字节(试图分配63981406字节)

php.ini中的memory_limit已经设置为128MB,但它仍然无法正常工作。我是否需要将此值设置得更高?

1 个答案:

答案 0 :(得分:3)

默认情况下,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 ...
}