[英]Get the http headers from current request in PHP
Is it possible to get the http headers of the current request with PHP? 是否可以使用PHP获取当前请求的http标头? I am not using Apache as the web-server, but using nginx.
我不是使用Apache作为Web服务器,而是使用nginx。
I tried using getallheaders()
but I am getting Call to undefined function getallheaders()
. 我尝试使用
getallheaders()
但我正在Call to undefined function getallheaders()
。
Taken from the documentation someone wrote a comment ... 从文档中取出有人撰写评论 ......
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;
}
}
Improved @Layke his function, making it a bit more secure to use it: 改进了@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;
}
}
(wished I could just add this as a comment to his answer but still building on that reputation thingy -- one of my first replies) (希望我能把这个作为评论添加到他的答案中,但仍然建立在那个声誉上 - 我的第一个回复之一)
您可以将服务器升级到PHP 5.4,从而可以通过fastcgi访问getallheaders() ,或者只需使用foreach
循环和一个小正则表达式解析$ _SERVER所需的内容。
Combined getallheaders() + apache_request_headers() for nginx 为nginx组合getallheaders()+ apache_request_headers()
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;
}
This issue was finally addressed in PHP 7.3.0, check release notes . 这个问题最终在PHP 7.3.0中得到解决,请查看发行说明 。
Fixed bug #62596 (getallheaders() missing with PHP-FPM).
修复了错误#62596 (PHP-FPM缺少getallheaders())。
This should work: 这应该工作:
<?php
print_r(
array_intersect_key(
$_SERVER,
array_flip(
preg_grep(
'/^HTTP_/',
array_keys($_SERVER),
0
)
)
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.