问题
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,
回答1:
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;
}
回答2:
try comment this curl_setopt($ch, CURLOPT_FILE, $fh);
来源:https://stackoverflow.com/questions/7126841/php-curlopt-writefunction-doesnt-appear-to-be-working