如果我执行设置为遵循重定向并返回 header 的 cURL 请求,它会返回所有重定向的 header 。
我只想返回最后一个 header (和内容主体)。我该如何实现?
最佳答案
另一种方式:
$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>';
当然,你还需要更多的错误检查,比如超时等。
关于php - 如何使用 PHP 的 curl 函数从上次重定向中获取 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3326774/