我应该如何读取PHP中的任何头文件?
例如,自定义标题:X-Requested-With
。
发布于 2012-07-29 20:45:21
您应该可以在$_SERVER
全局变量中找到所有HTTP头,前缀为HTTP_
uppercased,并用破折号(-)替换为下划线(_)。
例如,您的X-Requested-With
可以在以下位置找到:
$_SERVER['HTTP_X_REQUESTED_WITH']
从$_SERVER
变量创建关联数组可能比较方便。这可以通过几种样式来完成,但这里有一个输出驼峰键值的函数:
$headers = array();
foreach ($_SERVER as $key => $value) {
if (strpos($key, 'HTTP_') === 0) {
$headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
现在只需使用$headers['XRequestedWith']
来检索所需的标头。
$_SERVER
上的PHP手册:http://php.net/manual/en/reserved.variables.server.php
发布于 2013-01-26 00:15:08
从PHP5.4.0开始,您可以使用getallheaders
函数,该函数以关联数组的形式返回所有请求头:
var_dump(getallheaders());
// array(8) {
// ["Accept"]=>
// string(63) "text/html[...]"
// ["Accept-Charset"]=>
// string(31) "ISSO-8859-1[...]"
// ["Accept-Encoding"]=>
// string(17) "gzip,deflate,sdch"
// ["Accept-Language"]=>
// string(14) "en-US,en;q=0.8"
// ["Cache-Control"]=>
// string(9) "max-age=0"
// ["Connection"]=>
// string(10) "keep-alive"
// ["Host"]=>
// string(9) "localhost"
// ["User-Agent"]=>
// string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) [...]"
// }
早些时候,此函数仅在PHP作为Apache/NSAPI模块运行时才起作用。
发布于 2017-09-04 18:23:01
我使用的是CodeIgniter,并使用下面的代码来获取它。可能对将来的某些人有用。
$this->input->get_request_header('X-Requested-With');
https://stackoverflow.com/questions/541430
复制相似问题