Get the http headers from current request in PHP

2019-01-16 18:14发布

问题:

Is it possible to get the http headers of the current request with PHP? I am not using Apache as the web-server, but using nginx.

I tried using getallheaders() but I am getting Call to undefined function getallheaders().

回答1:

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; 
    } 
} 


回答2:

Improved @Layke his function, making it a bit more secure to use it:

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)



回答3:

You can upgrade your server to PHP 5.4 thereby giving you access to getallheaders() via fastcgi or simply parse what you need out of $_SERVER with a foreach loop and a little regex.



回答4:

Combined getallheaders() + apache_request_headers() for 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;
}


回答5:

This issue was finally addressed in PHP 7.3.0, check release notes.

Fixed bug #62596 (getallheaders() missing with PHP-FPM).



回答6:

This should work:

<?php 

print_r(
  array_intersect_key(
    $_SERVER,
    array_flip(
      preg_grep(
        '/^HTTP_/', 
        array_keys($_SERVER),
        0
      )
    )
  )
);