How do I read any request header in PHP


How should I read any header in PHP?

For example the custom header: X-Requested-With.

2/6/2015 8:50:44 AM

Accepted Answer

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

// 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):


$headers = apache_request_headers();

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

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

function getRequestHeaders() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if (substr($key, 0, 5) <> 'HTTP_') {
        $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.

7/5/2017 10:38:28 AM


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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow