Get Browser Type Get Browser Type with PHP / Böngésző lekérdezése PHP-ben
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.
- Code: Select all
<?php
/*
Author: Daniel Kassner
Website: http://www.danielkassner.com
*/
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 8' => '(MSIE 8\.[0-9]+)',
'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:
- Code: Select all
<?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
If you wanted to see a larger list of browser user agent strings to expand this code you can find them at: