简体   繁体   English

PHP CURLOPT_WRITEFUNCTION似乎不起作用

[英]PHP CURLOPT_WRITEFUNCTION doesn't appear to be working

I'm trying to read just one chunk of a stream of data using curl. 我正在尝试使用curl读取一小部分数据流。

Ideally I would like to just retreive the first image in the stream and write that to a jpg file. 理想情况下,我只想获取流中的第一张图像并将其写入jpg文件。

I'm attempting to do this using WRITEFUNCTION and returning -1 if the length of the stream > say 20000. 我正在尝试使用WRITEFUNCTION来执行此操作,并且如果流的长度> 20000,则返回-1。

function receiveResponse($ch,$string) {
    $length = strlen($string);
    if($length >= 20000) { return -1; }
    return $length;
}

$ch = curl_init('http://<url>/videostream.cgi');
curl_setopt($ch, CURLOPT_USERPWD, '<user>:<password>');
curl_setopt($ch, CURLOPT_WRITEFUNCTION, "receiveResponse");
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);

However the stream just continues to write to the file which ends up getting larger and larger in file size. 但是,流只是继续写入文件,最终文件变得越来越大。

Am i doing something horribly wrong? 我做错什么了吗?

Regards, 问候,

Lets look at option description from this manual http://www.php.net/manual/en/function.curl-setopt.php : 让我们从本手册http://www.php.net/manual/zh/function.curl-setopt.php中查看选项说明:

CURLOPT_WRITEFUNCTION The name of a callback function where the callback function takes two parameters. CURLOPT_WRITEFUNCTION回调函数的名称,其中回调函数带有两个参数。 The first is the cURL resource, and the second is a string with the data to be written. 第一个是cURL资源,第二个是包含要写入数据的字符串。 The data must be saved by using this callback function. 必须使用此回调函数保存数据。 It must return the exact number of bytes written or the transfer will be aborted with an error. 它必须返回写入的确切字节数,否则传输将因错误而中止。

So, it means what a response can be split into several pieces of data. 因此,这意味着可以将响应拆分成几段数据。 For appropriate receiving of first 20000 bytes you must add $full_length counter: 为了正确接收前20000个字节,必须添加$ full_length计数器:

$full_length = 0;
function receiveResponse($ch,$string) use (&$full_length) {
    $length = strlen($string);
    $full_length += $length;
    if($full_length >= 20000) { return -1; }
    return $length;
}

尝试对此curl_setopt($ ch,CURLOPT_FILE,$ fh)发表评论;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM