No More CSS Hacks: PHP Browser Detection

You can’t make your page render correctly in every browser. It just isn’t possible. Between several versions of the bug-ridden Internet Explorer (why can’t Microsoft just switch to Gecko or WebKit?) and a sprinkling of older browsers, there are too many bases to cover. Internet Explorers 6 and prior are notorious for their bad CSS implementations (IE7 is better, but it still has a ways to go), and if you tweak your CSS to look right in them, chances are you’ll create another problem somewhere else. When does the endless cycle of fixing things end? When you give up and say “it’s just not going to work in all browsers.” Now, you don’t want to give up too soon, since there are still a lot of people on IE6, but you have to know when to call it quits.

And don’t forget about mobile browsers. Sure, their improving, like Apple’s mobile Safari browser on the iPhone, but it’s still a lot easier to use a mobile-specific version of a site than zooming and scrolling around on the tiny screen.

As usual, PHP has a solution. That solution comes in the form of the global variable $_SERVER['HTTP_USER_AGENT']. It holds a string that contains a bit of information about the browser and platform a user us using. By searching through the string, you can figure out what browser your users are browsing with, and write-in the right code depending on the browser. You can do this in as simple, or as complicated, of a way as you want.

You can simply write-in a call to a different stylesheet, or in the case of the iPhone, an entirely different template. Using echo, header(), and include(), you have plenty of different ways to do this. Here is a simple example:

$browser = strtolower($_SERVER['HTTP_USER_AGENT']);

if (strpos($browser, 'msie')) {
include 'internetexploder.php';
else {
include 'normal.php';

This is a great way to support old browsers. You can just feed them a simpler template.

Further Reading

  • gre

    how to do in html?any suggest? thanks.

  • Matt

    You could do it with JavaScript, but it’s not as reliable as PHP, since some people turn off JavaScript in their browser. Example here:

  • danny

    it's helpful, thanks.

  • Peter

    There should be strpos($browser, ‘msie’)!==false

  • John

    I have to say I love the “internetexploder.php” file name. Couldn’t stop laughing

    • Matt

      I picked it up from an old PC World or PC Magazine issue from a few years back. There was an article on how to change the string “Internet Explorer” system-wide through the registry. They used “Internet Exploder” as an example and I thought it was hilarious.