Every time you use your browser to access a website a User-Agent header is sent to the respective server.
Detecting user agents on the server can be useful for many reasons.
1. Browsers Quirks – Despite the standardization in browsers, there will remain some quirks in various browsers that you will need to iron out on a regular basis.
2. Personalize Content – It may be required to deliver different type of content depending on the browser type (although it is usually not recommended); whether mobile or otherwise.
3. Illegal Access – Prevent bandwidth hogging bots and poorly programmed clients from downloading your content.
Below is a sample header for my site when using Firefox.
http://www.codediesel.com/ GET / HTTP/1.1 Host: www.codediesel.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:18.104.22.168) Gecko/2009011913 Firefox/3.0.6 FirePHP/0.2.4 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive
PHP already has a builtin function – get_browser() that lets you determine the capabilities of the user’s browser, but it requires a browscap.ini to be installed, which sadly is not bundled with PHP, and also the function can slow down your php script. The other way to get a user agent is to use php server variables like below,
In this post we will use the Net_UserAgent_Detect Pear package to determine user agents.
Net_UserAgent_Detect being a Pear package we will use the Pear installer as below. I recommend to always use the Pear installer to download packages rather than downloading it manually as the Pear installer automatically downloads any dependent packages.
pear install Net_UserAgent_Detect-2.5.1
Usage is quite simple. For example the following code:
will return the following string on Firefox 3.0.6: This can be quite useful if you need to log the users browser or OS type.
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:22.214.171.124) Gecko/2009011913 Firefox/3.0.6 FirePHP/0.2.4
getUserAgent() is only one of the many methods available in the class.
"; echo('OS String: '.Net_UserAgent_Detect::getOSString())."
Some other useful functions to directly test the type of browser are:
So to detect if the user is running Firefox:
$browser = Net_UserAgent_Detect::isNetscape();