2012-11-05 72 views
30

是否可以使用PHP獲取當前請求的http標頭?我是而不是使用Apache作爲Web服務器,但使用nginx。從PHP中的當前請求獲取http標頭

我試過使用getallheaders()但我得到Call to undefined function getallheaders()

+0

,你可以在我的答案看你還是可以使用getallheaders()可以 – gabrielem

+0

去投票在這裏:https://bugs.php.net/bug.php?id = 62596 – Bell

回答

3

你可以升級你的服務器PHP 5.4,從而使您通過FastCGI的訪問getallheaders()或簡單地分析你所需要的出$ _ SERVER與foreach環和一點點正則表達式。

+1

'nginx'是否總是在FastCGI上運行?這就是爲什麼'getallheaders()'不能在PHP 5.3下工作嗎? –

+1

@BenHarold查看[getallheaders]的更新日誌(http://www.php.net/manual/en/function.getallheaders.php):_5.4:該功能在FastCGI下可用。以前,只有當PHP被安裝爲Apache模塊時才支持它._ –

+0

@FredWuerges我讀過更改日誌。這就是爲什麼我問了這些問題。要說得更好一點:nginx是否總是使用FastCGI,並且當爲nginx使用PHP 5.3或更早版本時,getallheaders()不起作用?這是否意味着當使用PHP 5.4和nginx時'getallheaders()'和'apache_request_headers()'工作? –

43

從文檔有人採取寫了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; 
    } 
} 
+1

感謝它的運作。但是你能解釋一下這個函數中'ucwords'和'strtolower'的用途嗎?有必要嗎 ? – Cone

+1

這個函數中的一個錯誤是,大寫頭如「DNT」(Do Not Track)將變成「Dnt」 - 這不是原生getallheaders()的情況, – Bell

20

改進@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; 
    } 
} 

(希望我能剛添加這個作爲他的回答評論,但仍然建立在這種聲譽thingy - 我的第一個答覆之一)

1

Combined get allheaders()+ 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; 
}