How do I read any request header in PHP How do I read any request header in PHP php php

How do I read any request header in PHP


IF: you only need a single header, instead of all headers, the quickest method is:

<?php// Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE (and with '-' replaced by '_')$headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX'];


ELSE IF: you run PHP as an Apache module or, as of PHP 5.4, using FastCGI (simple method):

apache_request_headers()

<?php$headers = apache_request_headers();foreach ($headers as $header => $value) {    echo "$header: $value <br />\n";}


ELSE: In any other case, you can use (userland implementation):

<?phpfunction getRequestHeaders() {    $headers = array();    foreach($_SERVER as $key => $value) {        if (substr($key, 0, 5) <> 'HTTP_') {            continue;        }        $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));        $headers[$header] = $value;    }    return $headers;}$headers = getRequestHeaders();foreach ($headers as $header => $value) {    echo "$header: $value <br />\n";}


See Also:
getallheaders() - (PHP >= 5.4) cross platform edition Alias of apache_request_headers()apache_response_headers() - Fetch all HTTP response headers.
headers_list() - Fetch a list of headers to be sent.


$_SERVER['HTTP_X_REQUESTED_WITH']

RFC3875, 4.1.18:

Meta-variables with names beginning with HTTP_ contain values read from the client request header fields, if the protocol used is HTTP. The HTTP header field name is converted to upper case, has all occurrences of - replaced with _ and has HTTP_ prepended to give the meta-variable name.


You should find all HTTP headers in the $_SERVER global variable prefixed with HTTP_ uppercased and with dashes (-) replaced by underscores (_).

For instance your X-Requested-With can be found in:

$_SERVER['HTTP_X_REQUESTED_WITH']

It might be convenient to create an associative array from the $_SERVER variable. This can be done in several styles, but here's a function that outputs camelcased keys:

$headers = array();foreach ($_SERVER as $key => $value) {    if (strpos($key, 'HTTP_') === 0) {        $headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;    }}

Now just use $headers['XRequestedWith'] to retrieve the desired header.

PHP manual on $_SERVER: http://php.net/manual/en/reserved.variables.server.php