Palm Tungsten E2, iSync, and Bluetooth »

Browser detection with PHP

Ah, browser detection. While there are a ton of ways of doing browser detection (most with Javascript), there’s a very simple way of doing it if you’re using PHP—the get_browser() function.

Note: From the PHP documentation for get_browser():

In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.

browscap.ini is not bundled with PHP, but you may find an up-to-date php_browscap.ini file here.

While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

get_browser() has been around since PHP 3, and it provides a really easy way of getting information about a user’s browser (particularly, which browser it is). The only thing you need to do in order to use get_browser() is to grab browscap.ini stick it somewhere on the filesystem (such as /usr/local/etc/php/ or /etc/php/) and tell php.ini where it is. Once you’ve done that, restart Apache, and do something like this in your code:

To detect IE:

$browser = get_browser();
if($browser->browser == 'IE') {
    [ do stuff ]
} else {
    [do other stuff ]
}

To detect Safari:

$browser = get_browser();
if($browser->browser == 'Safari') {
    [ do stuff ]
} else {
    [do other stuff ]
}

To detect Firefox:

$browser = get_browser();
if($browser->browser == 'Firefox') {
    [ do stuff ]
} else {
    [do other stuff ]
}

That’s about all there is to it. For more information, see the get_browser() documentation.

Comments are closed.