使用PHP获取当前请求的http头部是否可能? 我没有使用Apache作为Web服务器,而是使用nginx。
我尝试使用getallheaders()
方法,但我收到了Call to undefined function getallheaders()
的错误信息。
使用PHP获取当前请求的http头部是否可能? 我没有使用Apache作为Web服务器,而是使用nginx。
我尝试使用getallheaders()
方法,但我收到了Call to undefined function getallheaders()
的错误信息。
摘自文档,有个人写了一篇评论...
if (!function_exists('getallheaders'))
{
function getallheaders()
{
$headers = array ();
foreach ($_SERVER as $name => $value)
{
if (substr($name, 0, 5) == 'HTTP_')
{
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
ucwords
和 strtolower
的目的是什么吗?它们是否必要? - Michal S.改进了@Layke的函数,使其更加安全易用:
if (!function_exists('getallheaders')) {
function getallheaders()
{
if (!is_array($_SERVER)) {
return array();
}
$headers = array();
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
我希望我能够将这个作为对他答案的评论,但是还在努力提高声望 -- 这是我最初的回复之一。
将getallheaders()和apache_request_headers()结合在一起用于nginx
function get_nginx_headers($function_name='getallheaders'){
$all_headers=array();
if(function_exists($function_name)){
$all_headers=$function_name();
}
else{
foreach($_SERVER as $name => $value){
if(substr($name,0,5)=='HTTP_'){
$name=substr($name,5);
$name=str_replace('_',' ',$name);
$name=strtolower($name);
$name=ucwords($name);
$name=str_replace(' ', '-', $name);
$all_headers[$name] = $value;
}
elseif($function_name=='apache_request_headers'){
$all_headers[$name] = $value;
}
}
}
return $all_headers;
}
foreach
循环和一些正则表达式从$_SERVER中解析出您需要的内容。nginx
是否总是运行在 FastCGI 上?这就是为什么 getallheaders()
在 PHP 5.3 下无法工作的原因吗? - Ben Haroldgetallheaders()
无法工作的原因吗?这是否意味着在使用PHP 5.4和nginx时,getallheaders()
和apache_request_headers()
都可以正常工作? - Ben Harold这应该可以工作:
<?php
print_r(
array_intersect_key(
$_SERVER,
array_flip(
preg_grep(
'/^HTTP_/',
array_keys($_SERVER),
0
)
)
)
);