从PHP中获取当前请求的http标头

Jus*_*tin 41 php nginx http-headers

是否可以使用PHP获取当前请求的http标头?我不是使用Apache作为Web服务器,而是使用nginx.

我尝试过使用,getallheaders()但我得到了Call to undefined function getallheaders().

Lay*_*yke 47

从文档中取出有人撰写评论 ......

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; 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

  • 此函数中的一个错误是"DNT"(Do Not Track)等大写标题将变为"Dnt" - 这不是本机getallheaders()的情况 (2认同)
  • 此功能未显示“授权” ...知道吗? (2认同)

小智 24

改进了@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

(希望我能把这个作为评论添加到他的答案中,但仍然建立在那个声誉之上 - 我的第一个回复之一)


Chr*_*man 3

您可以将服务器升级到 PHP 5.4,从而可以通过 fastcgi 访问getallheaders()foreach ,或者只需使用循环和一些正则表达式从 $_SERVER 中解析您需要的内容。

  • 目前在 PHP7 上 getallheaders 不适用于 FastCGI 下的 nginx (7认同)
  • 这在 nginx 上仍然不起作用,getallheaders 归档在 PHP 文档中的 apache 函数下,因为它仅在 php 5.5 和 nginx 上确认为 Apache (4认同)