开发者

PHP CURLOPT_WRITEFUNCTION doesn't appear to be working

I'm trying to read just one chunk of a stream of data using curl.

Ideally I would like to just retreive the first image in the stream and write that to a jpg file.

I'm attempting to do this using WRITEFUNCTION and returning -1 if the length of the stream > say 20000.

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_exe开发者_高级运维c($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:

CURLOPT_WRITEFUNCTION The name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. 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:

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


try comment this curl_setopt($ch, CURLOPT_FILE, $fh);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜