PHP and browser detection

By | July 22, 2011

One of the things you might encounter as a web developer is detection of the browser that a visitor is using. In my specific case this was needed since I wanted to use some CSS3 styling, but only if the browser was capable. In all other cases the visitor had to see the CSS2 optimized page.

So I started looking into a way to let my web application determine what browser was visiting and what capabilities it had. Since this was for the new WordPress theme I’m developing it had to be in PHP and be sorta light-weight.

First thing was to figure out the basic browser that was visiting. This can be done by doing a simple strpos call in PHP on the user agent property. Having a list of the various user agents helped, I found just such a list at UserAgentString. A brief summary for some common browsers is below.

  $user_agent = $_SERVER['HTTP_USER_AGENT'];
  $IE        = strpos($this->_user_agent, 'MSIE') > -1;
  $IPad      = strpos($this->_user_agent, 'iPad') > -1;
  $Firefox   = strpos($this->_user_agent, 'Firefox/') > -1;
  $Chrome    = strpos($this->_user_agent, 'Chrome/') > -1;
  $Opera     = strpos($this->_user_agent, 'Opera/') > -1;
  $Android = strpos($this->_user_agent, 'Android') > -1;

As you can see determining the basic browser type is pretty simple. But to be able to determine if CSS3 is supported you will also need to locate the version of the browser. Keeping in mind that IE9+, Firefox 4+, Opera 10+ and Chrome are the only versions that support CSS3. The check for this is slightly different for each version. But you can do it easily with a regular expresion.

 // For all non IE browsers
 $locator;
 if ($Firefox) $locator = "Firefox/";
 if ($Android) $locator = "Androids";
 if ($Chrome) $locator = "Chrome/";
 if ($Opera) $locator = "Version/";
 preg_match('/'.$locator.'([0-9]{1,4}(.[0-9]{1,3})+)/', $user_agent, $version);

 // For IE
 preg_match('/MSIEs([0-9]{1,2}.[0-9]{1,2})/', $user_agent, $version);
 if (count($version) > 1) $version = $version[1];
 else $version = 0;

Having the version and the type of browser allows us to do all kinds of fancy browser specific stuff. Mostly introduce hacks for IE7 (yes many are needed), or add CSS3 support.

Leave a Reply