0

I am using the curl option CURLOPT_HEADERFUNCTION along with a closure to perform some basic data manipulation. As per the php docs, the function / callback must return the length of the header on each call.

    $headers = [];

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADERFUNCTION, function($curl, $headerLine) use (&$headers) {
        $headers[] = $headerLine;

        return strlen($headerLine);
    });

    $response = curl_exec($curl);
    curl_close($curl);

    return $headers;

I am using references to return the value which works fine. I am just curious if there are other ways to return this value without using references or using a callback?

myol
  • 8,857
  • 19
  • 82
  • 143

1 Answers1

2

You can specify the callback function to be a class method:

curl_setopt($curl, CURLOPT_HEADERFUNCTION, array($this, 'someOtherFunction'));

In that other function, you can have access to anything $this has access to:

protected function someOtherFunction($curl, $headerLine)
{
    $this->headers[] = $headerLine;

    return strlen($headerLine);
}

* This answer assumes you're inside of a class context to begin with

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
  • Thanks but I was wondering if it is possible without a callback function either. Interesting you can just use `$this`, I think I used `&$this` initially. – myol Feb 04 '16 at 09:13
  • 1
    If you want to use `CURLOPT_HEADERFUNCTION` then it takes a callback, no way around that. If the only thing you want to do is look at the headers of a response, check out [this answer](http://stackoverflow.com/a/9183272/697370) – Jeff Lambert Feb 04 '16 at 12:53