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.
Execute your request
Take the length of the header from curl_getinfo
s return value
Retrieve the part between the last \r\n\r\n
(but before the end of the header) and the end of the header as last header
// Step 1: Execute
$fullResponse = curl_exec($ch);
// Step 2: Take the header length
$headerLength = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
// Step 3: Get the last header
$header = substr($fullResponse, 0, $headerLength - 4);
$lastHeader = substr($header, (strrpos($header, "\r\n\r\n") ?: -4) + 4);
Of course if you have PHP < 5.3 you have to expand the elvis operator to an if/else construct.
Late answer, but maybe more simple way to;
$result = explode("\r\n\r\n", $result);
// drop redirect etc. headers
while (count($result) > 2) {
array_shift($result);
}
// split headers / body parts
@ list($headers, $body) = $result;