user2029890
user2029890

Reputation: 2713

PHP curl how to retrieve headers when using Proxy. CURLOPT_HEADERFUNCTION?

I'm connecting to a site using a proxy like this:

$curl = curl_init();
curl_setopt($curl, CURLOPT_PROXY, $proxy);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
curl_setopt($curl, CURLOPT_HEADER, TRUE);
$result = curl_exec ($curl);

Problem is that CURLOPT_HEADER is returning the headers from the proxy connection whereas I need the headers from the actual request to the URL. I believe the solution involves using CURLOPT_HEADERFUNCTION but I don't understand how to use it.

I tried this (taken from elsewhere on SO):

curl_setopt($curl, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");

using function:

function HandleHeaderLine($curl, $header_line ) {
    echo "<br>YEAH: ".$header_line; // or do whatever
    return strlen($header_line);
}

But it seems I can only return the number of bytes. I'm unsure how to get the actual value. In my situation I just want the Location Header.

Thank you.

Upvotes: 4

Views: 1746

Answers (1)

laketuna
laketuna

Reputation: 4080

The anonymous callback for CURLOPT_HEADERFUNCTION will need access to the variable in which you want to store the header information. There are a few different approaches, but here some examples:

Using use:

$headers = [];
...
function HandleHeaderLine($curl, $header_line) use (&$headers)
{
    ...
    if ($isHeaderIWant) {
        $header[] = 'some info';
    }
    return strlen($header_line);
}

Using class property:

private $headers = [];
...
function HandleHeaderLine($curl, $header_line)
{
    ...
    if ($isHeaderIWant) {
        $this->header[] = 'some info';
    }
    return strlen($header_line);
}

Upvotes: 2

Related Questions