简体   繁体   中英

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_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 :

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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