PHP: How to check UserAgent?

How to know which browser the user using while s/he browsing my page? Lets know how to do it using PHP. You can get the user's browser identifier by using the below PHP code
$agent = $_SERVER['HTTP_USER_AGENT']

It is always best to use isset() function to grab the value from the variable, otherwise you'll get error if the value is not set. In that case it will be
if(isset($_SERVER['HTTP_USER_AGENT'])){
$agent = $_SERVER['HTTP_USER_AGENT'];
}

Now lets analyze about the user's browser. From the user agent string, you can easily differentiate the browser name of user. For example if you want to provide different types of PHP code for Mozilla users. To identify the Mozilla user, code will be
if(preg_match('/^Mozilla\/.*?Gecko/i',$agent)){
print "Firefox user.";
// process here for firefox browser
}

For other browsers, you just need to change the regular expression. Below are the two regular expression for Opera and Internet Explorer.
/^Opera\//i
/^Mozilla\/.*Gecko/i
Here /i means the string is case insensitive.

For more PHP related topics, here is my other posts http://icfun.blogspot.com/search/label/php

Comments

Salsan Jose said…
Thanks for the code. i was looking for the code to serve different styles for different browsers. Thanks anyway..
_

Find PHP Experts In PHP Discussion Forum.
Rencontres said…
Hi,
There is a mistake made for the code about IE : You've put the regular expression for Mozilla again instead of Internet Explorer !
Anonymous said…
What Recontres said :-)

What *is* the string to use for IE?
Andrew said…
I found http://tinytop.mobi, which I think is the best detector real user agent script