如何为 PHP cURL 下载设置最大大小限制? [英] How to set a maximum size limit to PHP cURL downloads?
问题描述
PHP cURL 下载是否有最大大小限制?IE.当传输达到一定的文件限制时,cURL 会退出吗?
Is there a maximum size limit to PHP cURL downloads? ie. will cURL quit when transfer reaches a certain file limit?
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
用于下载远程图像的站点.我想确保 cURL 在达到某个限制时会停止.
It's for a site that downloads remote images. I want to ensure that cURL will stop when it reaches a certain limit.
另外我的研究表明 getimagesize()
下载图像,返回它的大小,所以它不是一个选项.
Also my research shows getimagesize()
downloads the image, to return its size so its not an option.
推荐答案
我有另一个答案可以更好地解决这种情况,让后人留在这里.
CURLOPT_WRITEFUNCTION
对此有好处,但 CURLOPT_PROGRESSFUNCTION
是最好的.
CURLOPT_WRITEFUNCTION
is good for this but CURLOPT_PROGRESSFUNCTION
is the best.
// We need progress updates to break the connection mid-way
curl_setopt($cURL_Handle, CURLOPT_BUFFERSIZE, 128); // more progress info
curl_setopt($cURL_Handle, CURLOPT_NOPROGRESS, false);
curl_setopt($cURL_Handle, CURLOPT_PROGRESSFUNCTION, function(
$DownloadSize, $Downloaded, $UploadSize, $Uploaded
){
// If $Downloaded exceeds 1KB, returning non-0 breaks the connection!
return ($Downloaded > (1 * 1024)) ? 1 : 0;
});
请记住,即使 PHP.net 声明^ 对于 CURLOPT_PROGRESSFUNCTION
:
接受五个参数的回调.
我的本地测试只有四 (4) 个参数,因为第一个(句柄)不存在.
My local tests have featured only four (4) parameters as the 1st (handle) is not present.
这篇关于如何为 PHP cURL 下载设置最大大小限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!