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.

How can I fix it?

Elikill58
  • 4,050
  • 24
  • 23
  • 45
Joel
  • 2,185
  • 4
  • 29
  • 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
  • 8,856
  • 9
  • 52
  • 84
  • 2
    This php code is not valid. In PHP, the `use` keyword is used to import variables from the outer scope into closures (anonymous functions). However, in your code, you're trying to use it with a regular named function, which is not allowed. – Simon Apr 28 '23 at 02:29
-2

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

Chameron
  • 2,734
  • 8
  • 34
  • 46