How to get the headers from the last redirect with

2019-06-25 12:16发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

  1. Execute your request

  2. Take the length of the header from curl_getinfos return value

  3. 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.



回答4:

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;


标签: php http curl