如何设置PHP cURL下载的最大大小限制?

2022-08-30 22:58:11

PHP cURL 下载是否有最大大小限制?即。当传输达到一定文件限制时,cURL会退出吗?

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);

它适用于下载远程映像的站点。我想确保cURL在达到一定限制时会停止。

此外,我的研究表明下载图像,以返回其大小,因此它不是一个选项。getimagesize()


答案 1

我有另一个答案,可以更好地解决这种情况,留给后代留在这里。

CURLOPT_WRITEFUNCTION对此有好处,但CURLOPT_PROGRESSFUNCTION是最好的

// 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)个参数,因为第一个(句柄)不存在。


答案 2

服务器不支持范围标头。您可以做的最好的方法是在收到比所需更多的数据后立即取消连接。例:

<?php
$curl_url = 'http://steamcommunity.com/id/edgen?xml=1';
$curl_handle = curl_init($curl_url);

$data_string = "";
function write_function($handle, $data) {
global $data_string;
$data_string .= $data;
if (strlen($data_string) > 1000) {
    return 0;
}
else
    return strlen($data);
} 

curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($curl_handle, CURLOPT_WRITEFUNCTION, 'write_function');

curl_exec($curl_handle);

echo $data_string;

也许更干净地说,你可以使用http包装器(如果它使用--with-curlwrappers编译,这也将使用curl)。基本上,你会在循环中调用 fread,然后在获得的数据比你想要的多时在流上调用 fclose。如果禁用了传输流,您还可以使用传输流(使用 fsockopen 打开流,而不是 fopen 并手动发送标头allow_url_fopen)。


推荐