您的位置 首页 php

php获取发送给用户header信息的方法

服务器在向用户端发送信息时,都会携带默认的或者自定义好的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信息的方法

文章地址:https://www.zhihuclub.com/78860.shtml

关于作者: 智云科技

热门文章

网站地图