1

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,

Joel
  • 2,135
  • 4
  • 28
  • 56
  • 1
    Answer is very good. But just in case you're googling "PHP CURLOPT_WRITEFUNCTION doesn't appear to be working" and nothing helps you .... MAKE SURE THE OUTGOING PORTS FROM THE URL YOU TRY TO ACCESS ARE OPEN. – Mike O.O. Jan 28 '18 at 21:35

2 Answers2

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;
}
Denis Kreshikhin
  • 7,996
  • 8
  • 48
  • 81
-2

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

Chameron
  • 2,384
  • 8
  • 31
  • 45