Get request headers with PHP.

This is a short guide on how to get a client’s HTTP request headers using PHP. This can come in particularly useful if you are rolling your own custom logging solution.

Getting the request headers.

Let’s take a look at the following PHP function:

function getHeaderList() {
    //create an array to put our header info into.
    $headerList = array();
    //loop through the $_SERVER superglobals array.
    foreach ($_SERVER as $name => $value) {
        //if the name starts with HTTP_, it's a request header.
        if (preg_match('/^HTTP_/',$name)) {
            //convert HTTP_HEADER_NAME to the typical "Header-Name" format.
            $name = strtr(substr($name,5), '_', ' ');
            $name = ucwords(strtolower($name));
            $name = strtr($name, ' ', '-');
            //Add the header to our array.
            $headerList[$name] = $value;
        }
    }
    //Return the array.
    return $headerList;
}

In the function above, we loop through the $_SERVER superglobals array and pick out any of the HTTP headers that the client has sent to us.

We then change the name of the header into a more common format.
i.e. “HTTP_USER_AGENT” becomes “User-Agent” and so forth.

$_SERVER

In PHP, all HTTP headers that the client sent are stored in the $_SERVER superglobals array. However, they are usually named differently. For example: “Host” becomes “HTTP_HOST” and “Accept-Encoding” becomes “HTTP_ACCEPT_ENCODING”.

Friendly Reminder: Client headers cannot be trusted and you should never ever assume that headers such as “HTTP_USER_AGENT” will exist in the $_SERVER array. These headers can be easily spoofed, so rely on them at your own peril!