Álvaro González
Álvaro González

Reputation: 146540

Get only latest HTTP headers on redirection

Curl follows redirections nicely:

$fp = fopen($header, 'wb');
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_WRITEHEADER, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$content = curl_exec($ch);
curl_close($ch);
fclose($fp);

... but the header collection includes headers from all intermediate requests:

HTTP/1.1 301 Moved Permanently
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Location: http://example.net/
Content-Length: 14
Content-Type: text/html; charset=UTF-8

HTTP/1.1 301 Moved Permanently
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Location: http://example.org/
Content-Length: 14
Content-Type: text/html; charset=UTF-8

HTTP/1.1 200 OK
Date: Wed, 05 Jul 2017 16:39:31 GMT
Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k PHP/7.1.4
X-Powered-By: PHP/7.1.4
Content-Length: 5
Content-Type: text/html; charset=UTF-8

Since I'm often only interested in whatever I've finally fetched that's rather inconvenient because I need to parse the entire header set.

Is there a builtin setting/mechanism to discard previous headers on redirection or text parsing is the only way?

Upvotes: 1

Views: 47

Answers (1)

Dekel
Dekel

Reputation: 62626

Using the curl_getinfo function you can get the actual URL after the redirect:

CURLINFO_EFFECTIVE_URL

Usage example:

$last_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
if ($last_url === '...') {
    ...
}

Upvotes: 2

Related Questions