How to get the headers from the last redirect with

2019-06-25 11:43发布

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?

标签: php http curl
4条回答
神经病院院长
2楼-- · 2019-06-25 12:18

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.

查看更多
Bombasti
3楼-- · 2019-06-25 12:33

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.

查看更多
ら.Afraid
4楼-- · 2019-06-25 12:39
  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.

查看更多
Ridiculous、
5楼-- · 2019-06-25 12:39

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;
查看更多
登录 后发表回答