如何设置php curl下载的最大大小限制

Soj*_*ose 14 php curl

php curl下载是否有最大大小限制.即当转移达到某个文件限制时会卷曲退出吗?

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
Run Code Online (Sandbox Code Playgroud)

它用于下载远程图像的站点.想要确保卷曲在达到一定限度时停止.我的研究也显示getimagesize()下载图像,以返回其大小.所以它不是一个选择.

Cod*_*gry 28

我还有另一个答案,可以更好地解决这个问题.

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;
});
Run Code Online (Sandbox Code Playgroud)

请记住,即使PHP.net声明 ^ for CURLOPT_PROGRESSFUNCTION:

一个回调接受五个参数.

我的本地测试只有四(4)个参数,因为第一个(句柄)不存在.

  • 在我的情况下,回调真的有**五(5)个参数**.这只是说,必须小心并为自己测试功能. (3认同)
  • 在我的情况下,从回调返回非零会导致空下载结果.curl_error说:"Callback aborted".所以我不能以这种方式获取请求页面的有限部分. (2认同)

小智 6

服务器不支持 Range 标头。您能做的最好的事情就是当您收到的数据多于您想要的数据时立即取消连接。例子:

<?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;
Run Code Online (Sandbox Code Playgroud)

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