jump to navigation

Detecting user agents in php with a pear modul March 30, 2011

Posted 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 .
Host localhost
User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.1; el; rv: Gecko/20110319 Firefox/3.6.16 FirePHP/0.5
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language el-gr,el;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-7,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
x-insight activate
Cache-Control max-age=0

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:

require_once ‘Net/UserAgent/Detect.php’;

echo(‘Browser String: ‘.Net_UserAgent_Detect::getBrowserString()) .”” ;
echo(‘OS String: ‘.Net_UserAgent_Detect::getOSString()).”” ;
echo(‘Javascript: ‘.Net_UserAgent_Detect::getFeature(‘javascript’));



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s