Get Browser Type
By: Daniel
Have you ever wanted to create a stats application that identifies the users browser type? The following function will allow you to easily do just that. This function can be expanded by adding more values to the $browser array so you can match other browsers. This getBrowser() function parses the $_SERVER[’HTTP_USER_AGENT’] variable to get the current browser.
function getBrowser($userAgent) { // Create list of browsers with browser name as array key and user agent as value. $browsers = array( 'Opera' => 'Opera', 'Mozilla Firefox'=> '(Firebird)|(Firefox)', // Use regular expressions as value to identify browser 'Galeon' => 'Galeon', 'Mozilla'=>'Gecko', 'MyIE'=>'MyIE', 'Lynx' => 'Lynx', 'Netscape' => '(Mozilla/4\.75)|(Netscape6)|(Mozilla/4\.08)|(Mozilla/4\.5)|(Mozilla/4\.6)|(Mozilla/4\.79)', 'Konqueror'=>'Konqueror', 'SearchBot' => '(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)', 'Internet Explorer 7' => '(MSIE 7\.[0-9]+)', 'Internet Explorer 6' => '(MSIE 6\.[0-9]+)', 'Internet Explorer 5' => '(MSIE 5\.[0-9]+)', 'Internet Explorer 4' => '(MSIE 4\.[0-9]+)', ); foreach($browsers as $browser=>$pattern) { // Loop through $browsers array // Use regular expressions to check browser type if(eregi($pattern, $userAgent)) { // Check if a value in $browsers array matches current user agent. return $browser; // Browser was matched so return $browsers key } } return 'Unknown'; // Cannot find browser so return Unknown }
How to use this code:
echo getBrowser($_SERVER['HTTP_USER_AGENT']); $browserType = getBrowser($_SERVER['HTTP_USER_AGENT']); echo '<br />I am currently running '.$browserType.' as my web browser';
This would produce the following if I were(and am) running Mozilla Firefox:
Mozilla Firefox
I am currently running Mozilla Firefox as my web browser





(14 votes, average: 4.21 out of 5)
February 21st, 2007 at 8:41 pm
Nice tutorial! Works well
Thanks.
February 16th, 2008 at 7:07 am
Hey thank you for your tut . works great . made some mods to the code and got it working better
basicly i got it to say the os and the browser on one line . insted of it saying the os , browser , browser again .
Thanks