php - 如何使用 PHP 的 curl 函数从上次重定向中获取 header ?

标签 php http curl

如果我执行设置为遵循重定向并返回 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/

相关文章:

php - 在不使用 native 拆分或反转功能的情况下反转字符串中每个单词中的字母

php - 更快地了解 MySQL 数据库中的总行数的方法?

php - 使用php将字符串转换为逗号分隔的数组

linux - Bash 中的并行迭代 IP 地址

php - MySQL:使用相同连接对象的多个查询

php - 未知列 "in field list form "

json - HTTP 请求 "replay"是什么意思?

http - netsh http 添加 urlacl : add reservation for a group

c++ - 如何在 C++ 中使用带有 SFML 的 http 请求从 node.js 服务器获取数据?

linux - 从 URL 执行 bash 脚本