PHP中如何检查已设置的响应头(发送前)
获取PHP中已设置但未发送的响应头
当然可行!PHP确实没有内置的get_header()函数,但我们有几种可靠的方式来获取已经设置好、但还没发送给客户端的响应头——刚好符合你的需求,毕竟你已经知道headers_sent()只是用来检查头是否已发送,而不是获取头内容。
下面是两种常用的解决方案:
1. 通用方案:利用headers_list()封装自定义函数
headers_list()会返回所有已设置的响应头的字符串数组(格式为"Key: Value"),我们可以遍历这个数组,拆分出头的键和值,从而找到目标头:
function get_header($targetHeader) { // HTTP头大小写不敏感,统一转小写避免匹配问题 $targetHeader = strtolower($targetHeader); foreach (headers_list() as $header) { // 只拆分一次,避免值里包含冒号的情况 list($headerKey, $headerValue) = explode(': ', $header, 2); if (strtolower($headerKey) === $targetHeader) { return $headerValue; } } // 如果找不到目标头,返回null或者你想要的默认值 return null; } // 你的使用示例: header('Location: https://www.google.fr'); $location = get_header('Location'); echo $location; // 输出:https://www.google.fr
这个方案不依赖任何服务器环境,在PHP-FPM、Nginx、Apache等环境下都能正常工作。
2. Apache专属方案:apache_response_headers()
如果你运行在Apache服务器环境下,可以直接用apache_response_headers(),它会返回一个关联数组,键是头名称,值是头内容,使用起来更简洁:
// 注意:仅适用于Apache服务器 header('Location: https://www.google.fr'); $responseHeaders = apache_response_headers(); $location = $responseHeaders['Location'] ?? null; echo $location;
重要提示
不管用哪种方法,都要确保在响应头发送给客户端之前调用——也就是headers_sent()返回false的时候。一旦头已经发送,这些方法就无法获取到(因为头已经离开了PHP的控制范围)。
内容的提问来源于stack exchange,提问作者Hammerbot
相关产品推荐
相关产品推荐

