PHP: Browser identification

      No Comments on PHP: Browser identification

Not too long ago, I wrote a short tutorial on using ColdFusion to identify the user’s browser and add extra browser-specific CSS files. 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.

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!

Leave a Reply

Your email address will not be published. Required fields are marked *