02 May 2010

PHP: Quick & handy browser sniffer/checker function/class

Yes, you can check your visitor's browser using PHP! What's more, it never goes out of date! It automatically updates to recognise the lastest browsers. As much as I'd like to, I can't take credit for this one - it's the work of Jonathan Stoppani and makes browser sniffing with PHP an absolute breeze.

This class (named Browscap) is a great alternative to PHP's native get_broswer function which requires manual regular updating of a browser.ini definitions file. Instead, Browscap intermittently imports the latest browser definitions from browserproject.com  so that your scripts are always up to speed with the latest browser information.
Instructions and download below...

I've made a few edits to Jonathan's great class to make it a bit easier to implement. All you need to do is download the files below and add these two lines to your PHP script:

$browserInfo=checkbrowser(); //returns array of info on the browser (print_r($browserInfo) to view)

//alternatively, if you dont need all that array data:
$browser=checkbrowser('Browser'); //returns Case sensitive browser name (Firefox,Chrome,IE,etc)
$version=checkbrowser('Version'); //returns browser's version number (3.6, etc)

For details on what is returned in the array check out the Browscap website

» Download the modified Browscap file

NOTE: This is quite slow for one visitor every 10 days (which I can live with!) as it has to import the definitions file. Otherwise all data is cached and it should be nice and fast.
Cron Design Studio: Dublin based web design & software development