Detecting user agents in php with a pear modul March 30, 2011Posted by Tournas Dimitrios in PHP.
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.
- 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.
- Illegal Access – Prevent bandwidth hogging bots and poorly programmed clients from downloading your content. Below is a sample header for my local development environment when using Firefox .
|User-Agent||Mozilla/5.0 (Windows; U; Windows NT 5.1; el; rv:220.127.116.11) Gecko/20110319 Firefox/3.6.16 FirePHP/0.5|
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,
This article will explore another way of detecting browsers of visitors , we will use the Net_UserAgent_Detect Pear package to determine user agents . 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
Using this Class is quite simple. For example the following code will return a string with the browser type of your visitor . This can be quite useful if you need to log the users browser or OS type.:
require_once ‘Net/UserAgent/Detect.php’ ;
echo Net_UserAgent_Detect::getUserAgent() ;
getUserAgent() is only one of the many methods (24) available in the class , so open the class with your favorite editor or visit the official website . Another example:
echo(‘Browser String: ‘.Net_UserAgent_Detect::getBrowserString()) .”” ;
echo(‘OS String: ‘.Net_UserAgent_Detect::getOSString()).”” ;