User Tools

Site Tools


PHP: Browser identification

This article was originally published on August 22, 2008.

Not too long ago, I wrote a short tutorial on using ColdFusion to identify the user’s browser and add extra browser-specific CSS filesplugin-autotooltip__default plugin-autotooltip_bigColdFusion: Browser identification in web applications

I’m really, annoyingly, obsessively anal about browser compatibility in web design. Even if you’re convinced that none of your users will ever touch Opera, there’s no reason to not make sure your site is usable in Opera…or Lynx, or IE 5.5, or anything else.
. Today, I found myself in need of similar functionality for PHP. The code isn’t quite the same – PHP doesn’t have a direct clone of CF’s contains decision operator; you have to use the strstr string function instead. The general idea, however, is the same.

The following script will identify between Firefox, IE6, and IE7. Like my last post, I’ve added an extra piece that will include an ie.css file before including an IE version-specific stylesheet.

  $thePath = "/css";
  $absPath = $_SERVER['ABSOLUTE_PATH'] . "css";
  $theBrowser = $_SERVER['HTTP_USER_AGENT'];
  if(strstr($theBrowser, "Firefox")) {
    $browser = "firefox";
  elseif(strstr($theBrowser, "MSIE 7.0")) {
    $browser = "ie7";
  elseif(strstr($theBrowser, "MSIE 6.0")) {
    $browser = "ie6";
  if(file_exists($absPath . '/' . $browser . '.css')) {
    $css = '&lt;link rel="stylesheet" href="' . $thePath . '/' . $browser . '.css" /&gt;';
  if(strstr($browser, "ie")) {
    if(file_exists($absPath . '/ie.css')) {
      $css = '&lt;link rel="stylesheet" href="' . $thePath . '/ie.css" /&gt;' . $css;

The ABSOLUTE_PATH server variable tells us where our site is actually stored on the server; I added the name of the directory where my stylesheets are stored to the end of the variable and stuck it in a string called $absPath. You’ll need this absolute path to determine if a CSS file exists in the given directory. The relative link to my CSS directory is stored in $thePath and is used to link to the CSS file in my HTML.

When the code is done, I’m left with two variables I can use anywhere in my application: $browser is the short identifier for the user’s browser; $css contains the HTML to link to the additional stylesheet(s).

It’s the same concept with a slightly different implementation. Happy coding!