服务器在向用户端发送信息时,都会携带默认的或者自定义好的HTTP响应头,我们该如何利用php获取这些已经发送或者是将要发送的HTTP响应头呢?

PHP headers_list()函数
headers_list():函数返回已发送或者将要发送HTTP响应头
语法:
headers_list()
返回结果:
headers_list():函数没有参数,但它会返回一个数组。返回的数组中包含一个数字索引表,包含了要发送给客户端的header信息
php获取发送的HTTP响应头
例1:
代码:
<?php
setcookie("TestCookie","SomeValue");
header("X-Sample-Test: foo");
header('Content-type: text/plain');
// 打印发送的HTTP响应头
var_dump(headers_list());
?>打印结果:
array(4) {
[0]=>
string(24) "X-Powered-By: PHP/5.6.30"
[1]=>
string(32) "Set-Cookie: TestCookie=SomeValue"
[2]=>
string(18) "X-Sample-Test: foo"
[3]=>
string(38) "Content-type: text/plain;charset=UTF-8"
}例2:
代码:
<?php
header("X-Sample-Test: foo");
header('Content-type: text/plain');
$arr = headers_list();
foreach($arr as $a) {
echo $a;
}
?>打印结果:
X-Powered-By: PHP/5.6.30 X-Sample-Test: foo Content-type: text/plain;charset=UTF-8
扩展:
如果要判断是否已经发送HTTP响应头,请使用 headers_sent() 函数。
到此这篇关于php获取发送给用户header信息头的方法就介绍到这了。别想一下造出大海,必须先由小河川开始。更多相关php获取发送给用户header信息头的方法内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!




