Php how to get request headers

apache_request_headers

Fetches all HTTP request headers from the current request. Works in the Apache, FastCGI, CLI, and FPM webservers.

Parameters

This function has no parameters.

Return Values

An associative array of all the HTTP headers in the current request, or false on failure.

Changelog

Version Description
7.3.0 This function became available in the FPM SAPI.

Examples

Example #1 apache_request_headers() example

foreach ( $headers as $header => $value ) echo » $header : $value
\n» ;
>
?>

The above example will output something similar to:

Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 Host: www.example.com Connection: Keep-Alive

Notes

Note:

You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the available environment variables.

See Also

User Contributed Notes 6 notes

I didn’t found a replacement for apache_request_headers() in PHP::Compat (http://pear.php.net/package/PHP_Compat) so I wrote my own:

if( ! function_exists ( ‘apache_request_headers’ ) ) ///
function apache_request_headers () $arh = array();
$rx_http = ‘/\AHTTP_/’ ;
foreach( $_SERVER as $key => $val ) if( preg_match ( $rx_http , $key ) ) $arh_key = preg_replace ( $rx_http , » , $key );
$rx_matches = array();
// do some nasty string manipulations to restore the original letter case
// this should work in most cases
$rx_matches = explode ( ‘_’ , $arh_key );
if( count ( $rx_matches ) > 0 and strlen ( $arh_key ) > 2 ) foreach( $rx_matches as $ak_key => $ak_val ) $rx_matches [ $ak_key ] = ucfirst ( $ak_val );
$arh_key = implode ( ‘-‘ , $rx_matches );
>
$arh [ $arh_key ] = $val ;
>
>
return( $arh );
>
///
>
///
?>

Although we expect to see headers in mixed case, the standard RFC2616 demands that «field names are case-insensitive». PHP delivers the headers exactly untouched in whatever way the client sent them. Potentially you should expect to get any type of uppercase or lowercase or mixed.

Thus, if you want to be standards compliant, you must loop through every key and check it in a case-insensitive manner, instead of doing the obvious thing and using the name of the header as an array index.

There is a simple way to get request headers from Apache even on PHP running as a CGI. As far as I know, it’s the only way to get the headers «If-Modified-Since» and «If-None-Match» when apache_request_headers() isn’t available. You need mod_rewrite, which most web hosts seem to have enabled. Put this in an .htacess file in your web root:

Читайте также:  Java process 64 bit

RewriteEngine on
RewriteRule .* — [E=HTTP_IF_MODIFIED_SINCE:%]RewriteRule .* — [E=HTTP_IF_NONE_MATCH:%]

The headers are then available in PHP as
$_SERVER [ ‘HTTP_IF_MODIFIED_SINCE’ ];
$_SERVER [ ‘HTTP_IF_NONE_MATCH’ ];
?>

I’ve tested this on PHP/5.1.6, on both Apache/2.2.3/Win32 and Apache/2.0.54/Unix, and it works perfectly.

Note: if you use RewriteRules already for clean URLs, you need to put the above rules AFTER your existing ones.

Superglobal $_SERVER, used in all patches for missing getallheaders() contains only truly basic headers. To pass ANY header into PHP in any httpd environment, including CGI/FCGI just add rule (any number of rules) into .htaccess:

and the header with it’s value will appear for PHP as

And. just couldn’t hold off. Rewrtiting $_SERVER keys for replacing missing function really does not require RegExps, preg_matches or evals. Try this:
function getallheaders () <
foreach( $_SERVER as $K => $V ) < $a = explode ( '_' , $K );
if( array_shift ( $a )== ‘HTTP’ ) <
array_walk ( $a ,function(& $v )< $v = ucfirst ( strtolower ( $v ));>);
$retval [ join ( ‘-‘ , $a )]= $V ;>
> return $retval ; >
?>

The function apache_request_headers, doesn’t exist in FCGI PHP-FPM

// Drop-in replacement for apache_request_headers() when it’s not available

if ( ! function_exists ( ‘apache_request_headers’ ) ) function apache_request_headers () static $arrHttpHeaders ;
if ( ! $arrHttpHeaders )

// Based on: http://www.iana.org/assignments/message-headers/message-headers.xml#perm-headers
$arrCasedHeaders = array(
// HTTP
‘Dasl’ => ‘DASL’ ,
‘Dav’ => ‘DAV’ ,
‘Etag’ => ‘ETag’ ,
‘Mime-Version’ => ‘MIME-Version’ ,
‘Slug’ => ‘SLUG’ ,
‘Te’ => ‘TE’ ,
‘Www-Authenticate’ => ‘WWW-Authenticate’ ,
// MIME
‘Content-Md5’ => ‘Content-MD5’ ,
‘Content-Id’ => ‘Content-ID’ ,
‘Content-Features’ => ‘Content-features’ ,
);
$arrHttpHeaders = array();

foreach ( $_SERVER as $strKey => $mixValue ) if ( ‘HTTP_’ !== substr ( $strKey , 0 , 5 ) ) continue;
>

$strHeaderKey = strtolower ( substr ( $strKey , 5 ) );

if ( 0 < substr_count ( $strHeaderKey , '_' ) ) $arrHeaderKey = explode ( '_' , $strHeaderKey );
$arrHeaderKey = array_map ( ‘ucfirst’ , $arrHeaderKey );
$strHeaderKey = implode ( ‘-‘ , $arrHeaderKey );
> else $strHeaderKey = ucfirst ( $strHeaderKey );
>

if ( array_key_exists ( $strHeaderKey , $arrCasedHeaders ) ) $strHeaderKey = $arrCasedHeaders [ $strHeaderKey ];
>

$arrHttpHeaders [ $strHeaderKey ] = $mixValue ;
>

/** in case you need authorization and your hosting provider has not fixed this for you:
* VHOST-Config:
* FastCgiExternalServer line needs -pass-header Authorization
*
* .htaccess or VHOST-config file needs:
* SetEnvIf Authorization «(.*)» HTTP_AUTHORIZATION=$1
* to add the Authorization header to the environment for further processing
*/
if ( ! empty( $arrHttpHeaders [ ‘Authorization’ ] ) ) // in case of Authorization, but the values not propagated properly, do so 🙂
if ( ! isset( $_SERVER [ ‘PHP_AUTH_USER’ ] ) ) list( $_SERVER [ ‘PHP_AUTH_USER’ ], $_SERVER [ ‘PHP_AUTH_PW’ ] ) = explode ( ‘:’ , base64_decode ( substr ( $_SERVER [ ‘HTTP_AUTHORIZATION’ ], 6 ) ) );
>
>
>

// execute now so other scripts have little chance to taint the information in $_SERVER
// the data is cached, so multiple retrievals of the headers will not cause further impact on performance.
apache_request_headers ();
>

A slightly modified version from limalopex.eisfux.de. Fixes the missing Headers Content-Type and Content-Length and makes it Camel-Case.

Читайте также:  Colors in python matplotlib

if( ! function_exists ( ‘apache_request_headers’ ) ) function apache_request_headers () $arh = array();
$rx_http = ‘/\AHTTP_/’ ;
foreach( $_SERVER as $key => $val ) if( preg_match ( $rx_http , $key ) ) $arh_key = preg_replace ( $rx_http , » , $key );
$rx_matches = array();
// do some nasty string manipulations to restore the original letter case
// this should work in most cases
$rx_matches = explode ( ‘_’ , strtolower ( $arh_key ));
if( count ( $rx_matches ) > 0 and strlen ( $arh_key ) > 2 ) foreach( $rx_matches as $ak_key => $ak_val ) $rx_matches [ $ak_key ] = ucfirst ( $ak_val );
$arh_key = implode ( ‘-‘ , $rx_matches );
>
$arh [ $arh_key ] = $val ;
>
>
if(isset( $_SERVER [ ‘CONTENT_TYPE’ ])) $arh [ ‘Content-Type’ ] = $_SERVER [ ‘CONTENT_TYPE’ ];
if(isset( $_SERVER [ ‘CONTENT_LENGTH’ ])) $arh [ ‘Content-Length’ ] = $_SERVER [ ‘CONTENT_LENGTH’ ];
return( $arh );
>
>

  • Apache Functions
    • apache_​child_​terminate
    • apache_​get_​modules
    • apache_​get_​version
    • apache_​getenv
    • apache_​lookup_​uri
    • apache_​note
    • apache_​request_​headers
    • apache_​response_​headers
    • apache_​setenv
    • getallheaders
    • virtual

    Источник

    getallheaders

    This function is an alias for apache_request_headers() . Please read the apache_request_headers() documentation for more information on how this function works.

    Parameters

    This function has no parameters.

    Return Values

    An associative array of all the HTTP headers in the current request, or false on failure.

    Changelog

    Version Description
    7.3.0 This function became available in the FPM SAPI.

    Examples

    Example #1 getallheaders() example

    foreach ( getallheaders () as $name => $value ) echo » $name : $value \n» ;
    >

    See Also

    User Contributed Notes 9 notes

    it could be useful if you using nginx instead of apache

    if (! function_exists ( ‘getallheaders’ ))
    <
    function getallheaders ()
    <
    $headers = [];
    foreach ( $_SERVER as $name => $value )
    <
    if ( substr ( $name , 0 , 5 ) == ‘HTTP_’ )
    <
    $headers [ str_replace ( ‘ ‘ , ‘-‘ , ucwords ( strtolower ( str_replace ( ‘_’ , ‘ ‘ , substr ( $name , 5 )))))] = $value ;
    >
    >
    return $headers ;
    >
    >
    ?>

    A simple approach to dealing with case insenstive headers (as per RFC2616) is via the built in array_change_key_case() function:

    $headers = array_change_key_case(getallheaders(), CASE_LOWER);

    There’s a polyfill for this that can be downloaded or installed via composer:

    Beware that RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. Therefore, array keys of getallheaders() should be converted first to lower- or uppercase and processed such.

    dont forget to add the content_type and content_lenght if your are uploading file:

    function emu_getallheaders () <
    foreach ( $_SERVER as $name => $value )
    <
    if ( substr ( $name , 0 , 5 ) == ‘HTTP_’ )
    <
    $name = str_replace ( ‘ ‘ , ‘-‘ , ucwords ( strtolower ( str_replace ( ‘_’ , ‘ ‘ , substr ( $name , 5 )))));
    $headers [ $name ] = $value ;
    > else if ( $name == «CONTENT_TYPE» ) <
    $headers [ «Content-Type» ] = $value ;
    > else if ( $name == «CONTENT_LENGTH» ) <
    $headers [ «Content-Length» ] = $value ;
    >
    >
    return $headers ;
    >
    ?>

    chears magno c. heck

    apache_request_headers replicement for nginx

    if (! function_exists ( ‘apache_request_headers’ )) <
    function apache_request_headers () <
    foreach( $_SERVER as $key => $value ) <
    if ( substr ( $key , 0 , 5 )== «HTTP_» ) <
    $key = str_replace ( » » , «-» , ucwords ( strtolower ( str_replace ( «_» , » » , substr ( $key , 5 )))));
    $out [ $key ]= $value ;
    >else <
    $out [ $key ]= $value ;
    >
    >
    return $out ;
    >
    >
    ?>

    warning, at least on php-fpm 8.2.1 and nginx, getallheaders() will return «Content-Length» and «Content-Type» both containing emptystring, even for requests without any of these 2 headers. you can do something like

    retrieve token from header:

    function getAuthorizationHeader () $headers = null ;
    if (isset( $_SERVER [ ‘Authorization’ ])) $headers = trim ( $_SERVER [ «Authorization» ]);
    >
    elseif (isset( $_SERVER [ ‘HTTP_AUTHORIZATION’ ])) $headers = trim ( $_SERVER [ «HTTP_AUTHORIZATION» ]);
    >
    elseif ( function_exists ( ‘apache_request_headers’ )) $requestHeaders = apache_request_headers ();
    $requestHeaders = array_combine ( array_map ( ‘ucwords’ , array_keys ( $requestHeaders )), array_values ( $requestHeaders ));

    if (isset( $requestHeaders [ ‘Authorization’ ])) $headers = trim ( $requestHeaders [ ‘Authorization’ ]);
    >
    >

    function getBearerToken () $headers = getAuthorizationHeader ();

    if (!empty( $headers )) if ( preg_match ( ‘/Bearer\s(\S+)/’ , $headers , $matches )) return $matches [ 1 ];
    >
    >

    Due to the else part.
    >else <
    $out[$key]=$value;
    All server Variables are added to the headers list, and that’s not the desired outcome.

    • Apache Functions
      • apache_​child_​terminate
      • apache_​get_​modules
      • apache_​get_​version
      • apache_​getenv
      • apache_​lookup_​uri
      • apache_​note
      • apache_​request_​headers
      • apache_​response_​headers
      • apache_​setenv
      • getallheaders
      • virtual

      Источник

      How to Read Request Headers in PHP

      When typing a URL in the browser’s address bar and trying to access it, an HTTP request is sent to the server by the browser. It encompasses information in a text-record state including the type, the capabilities, user’s operation system, the browser generating the request, and more.

      Getting the request header, the web server sends an HTTP response head to the client.

      Below, we will show you how to read any request header in PHP.

      Using the getallheaders() Function

      To achieve what was described above, you can use the getllheaders() function.

      Let’s check out an example with its output:

       foreach (getallheaders() as $name => $value) < echo "$name: $value 
      "
      ; > ?>
      Host: 127.0.0.3:2025 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36 Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, image/apng, */*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US, en;q=0.9

      Using apache_request_headers() Function

      Now, let’s check out an example of using another helpful method that is the apache_request_headers() function:

       $header = apache_request_headers(); foreach ($header as $headers => $value) < echo "$headers: $value 
      \n"
      ; > ?>

      The output will look as follows:

      Host: 127.0.0.6:2027 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36 Accept: text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, image/apng, */*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: en-US, en;q=0.9

      Describing HTTP Headers

      An HTTP header is considered a code, which transfers the data between the browser and the web server.

      Generally, HTTP headers are used for the communication between the client and the server in both of the directions.

      Источник

Оцените статью