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.

<?php
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:

<?php
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

15 Votes | Average: 4.27 out of 515 Votes | Average: 4.27 out of 515 Votes | Average: 4.27 out of 515 Votes | Average: 4.27 out of 515 Votes | Average: 4.27 out of 5 (15 votes, average: 4.27 out of 5)
Loading ... Loading ...
del.icio.us:Get Browser Type digg:Get Browser Type spurl:Get Browser Type wists:Get Browser Type simpy:Get Browser Type newsvine:Get Browser Type blinklist:Get Browser Type furl:Get Browser Type reddit:Get Browser Type fark:Get Browser Type blogmarks:Get Browser Type Y!:Get Browser Type smarking:Get Browser Type magnolia:Get Browser Type segnalo:Get Browser Type

2 Responses to “Get Browser Type”

  1. Lee Says:

    Nice tutorial! Works well :)

    Thanks.

  2. Tony Says:

    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 :)

Leave a Reply

eXTReMe Tracker
geovisitors