Fetching HTTP request headers in PHP

Posted on January 17, 2006

Well, that was easy. I was looking for a way to fetch HTTP request headers in PHP, for the implementation of Conditional GET in an RSS module. PHP has this function, apache_request_headers(), which returns an array containing all the headers you could possibly need. Problem solved!

But; when the software you’re working on (in my case a content management system) has to work on both Linux/Apache and Windows/IIS servers, there’s a bit of a problem: Apache-functions won’t work if there’s no Apache to work with. Fortunately, you don’t need functions to fetch specific headers: PHP has already gathered them for you.

When a client requests a PHP-driven page on your web server, you can check for request headers in the $_SERVER array. For instance, the If-Modified-Since header is stored in $_SERVER[’HTTP_IF_MODIFIED_SINCE’]. This will work for every header you can think of: PHP just converts them all to the right variable. A header This-One-Doesnt-Exist becomes $_SERVER[’THIS_ONE_DOESNT_EXIST’] in PHP code. Just like that!

Comments

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name (required)

Email (required)

Website

Comments

2 Comments so far
  1. Gabe November 20, 2007 7:47 pm

    I wrote a PHP class that will retrieve the HTTP request headers. There are some HTTP headers that are not included in the $_SERVER superglobal array. This is mentioned in the blog.

  2. Brandon November 29, 2007 6:28 pm

    Thanks so much! It took me about 20 minutes of searching to find this, and it was very helpful. +5 informative!

    I’m adding mobile device support into my online timesheet system, and I really need to be able to read all the request headers to make sure I build pages properly for each phone.