16 Sep 2010

Server-side browser detection

Sometimes you can't rely on JavaScript to detect the browser the user is on. Luckily, PHP has built in browser detection. You might say "sure, i'll just look at the user agent and take out find 'Chrome' or 'Safari' in there to know what browser the client is using", but actually the user agents might include BOTH of those if you're running Chrome under Mac. The solution is a user supported library that you specify in your php configuration file (php.ini)

Open up your php.ini file, usually located at /etc/php.ini

If you can't find it, just create a a simple php script with the following code, and run it:

<?php
phpinfo();
?>

You should see the location outputted:

Open up that file and search for the line that says:

[browscap]
;browscap = extra/browscap.ini

You'll now need to download the latest version of the browscap.ini (and update it as often as you like to keep current).

I decided to store mine in /etc/php_browscap.ini , so I ran this:

wget http://browsers.garykeith.com/stream.asp?PHP_BrowsCapINI > /etc/php_browscap.ini

Now that it was there, I went into my php.ini configuration and changed the above code to:

[browscap]
browscap = /etc/php_browscap.ini

(Notice I removed the semicolon (;) at the beginning of the line to uncomment it)

Then simply restart your webserver. One of these might work for you:

sudo apachectl restart
sudo /etc/init.d/httpd restart
sudo /etc/init.d/apache2 restart

And open a new php script, to try this code:

<?php
$tmp = get_browser(null, true);
print_r($tmp);
?>

When I access that script from Google Chrome I see:

Array
(
    [browser_name_regex] => §^mozilla/5\.0 \(macintosh; .*; .*mac os x.*; .*; rv:1\.9\.2.*\) gecko/.* firefox/3\.6.*$§
    [browser_name_pattern] => Mozilla/5.0 (Macintosh; *; *Mac OS X*; *; rv:1.9.2*) Gecko/* Firefox/3.6*
    [parent] => Firefox 3.6
    [platform] => MacOSX
    [browser] => Firefox
    [version] => 3.6
    [majorver] => 3
    [minorver] => 6
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [javaapplets] => 1
    [javascript] => 1
    [cssversion] => 3
    [supportscss] => 1
    [alpha] => 
    [beta] => 
    [win16] => 
    [win32] => 
    [win64] => 
    [backgroundsounds] => 
    [cdf] => 
    [vbscript] => 
    [activexcontrols] => 
    [isbanned] => 
    [ismobiledevice] => 
    [issyndicationreader] => 
    [crawler] => 
    [aol] => 
    [aolversion] => 0
)

So I know that the client is connecting using Firefox running on a Mac, and some of the capabilities of the browser (it won't detect if those are disabled though by the user).

Voila, you're done!