Home > php > Get request headers sent by client in PHP

Get request headers sent by client in PHP

February 25th, 2009 Rahul Leave a comment Go to comments

A nice little function I found posted by “lazynitwit” on BlueHost forums:

01
function getHeaders()
02
{
03
    $headers = array();
04
    foreach ($_SERVER as $k => $v)
05
    {
06
        if (substr($k, 0, 5) == "HTTP_")
07
        {
08
            $k = str_replace('_', ' ', substr($k, 5));
09
            $k = str_replace(' ', '-', ucwords(strtolower($k)));
10
            $headers[$k] = $v;
11
        }
12
    }
13
    return $headers;
14
}  

The PHP function getallheaders() only works on Apache, and only if Apache has been installed as a module.

It turns out that this information is within the $_SERVER global variable, and can be parsed out.

This code is useful if, for instance, you want to differentiate between user browser requests and requests made through AJAX. Some of the JavaScript frameworks (jQuery, Prototype, YUI, MooTools) send a special header,

X-Requested-With: XMLHttpRequest

whenever a request is made. I have put this to use in my phpFreeChat chat box to allow channels to be specified in the URL as GET parameters.

via request headers php – bluehostforum.com.

VN:F [1.9.2_1090]
Rating: 4.7/5 (6 votes cast)
VN:F [1.9.2_1090]
Rating: +3 (from 3 votes)
Get request headers sent by client in PHP, 4.7 out of 5 based on 6 ratings
Categories: php Tags: , , , ,
  1. February 22nd, 2010 at 09:08 | #1

    Hi there, thank you for this function, it has saved me a headache since I know we’re deploying to nginx so would have come up sooner or later!

    Can you touch on why tyou used ucwords(strtolower($k))? I have a header that I am expecting and am passing through (kine of a php proxy for offline web service caching) that is called “API-KEY”, and after running through this function is “Api-Key”… is the server behavior on the other end of things generally going to standardize the headers to ucwords format, or was this just a personal preference? I just want to avoid messing up the headers when passing through if the receiving end “could be” case sensitive.

    Thanks!
    Chad

    VA:F [1.9.2_1090]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.2_1090]
    Rating: 0 (from 0 votes)
  2. August 9th, 2010 at 21:41 | #2

    was just about to write a function to do this, then i thought, “I might as well google it first”…

    then i found this :) thanks for the great function.

    VA:F [1.9.2_1090]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.2_1090]
    Rating: 0 (from 0 votes)
  1. No trackbacks yet.