If I execute a cURL request that is set to follow redirects and return the headers, it returns the headers for ALL of the redirects.
I only want the last header returned (and the content body). How do I achieve that?
If I execute a cURL request that is set to follow redirects and return the headers, it returns the headers for ALL of the redirects.
I only want the last header returned (and the content body). How do I achieve that?
Search the output for "HTTP/1.1 200 OK" in the beginning of the line - this is where your last request will begin. All others will give other HTTP return codes.
Here's another way:
$url = 'http://google.com';
$opts = array(CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HEADER => true);
$ch = curl_init($url);
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
$redirect_count = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = explode("\r\n\r\n", $response, $redirect_count + 2);
$last_header = $response[$redirect_count];
if ($status == '200') {
$body = end($response);
} else {
$body = '';
}
curl_close($ch);
echo '<pre>';
echo 'Redirects: ' . $redirect_count . '<br />';
echo 'Status: ' . $status . '<br />';
echo 'Last response header:<br />' . $last_header . '<br />';
echo 'Response body:<br />' . htmlspecialchars($body) . '<br />';
echo '</pre>';
Of course, you'll need more error checking, such as for timeout, etc.