A while back I was trying to use PHP's get_browser function, which should return an array of information. It takes the visitor's user agent value and parses it to do this. It turns out that in order to use get_browser you must have browscap configured correctly in your php.ini file. In my case this wasn't really an option since the server I was working on does not allow access to the ini file.
So, if you find yourself in a similar case then the best option will be to parse the user agent yourself. The following function is something I threw together to do just this. It will return a string revealing the visitor's browser and version.function getBrowser() {
$versmatch = '(\);)?(\w*[\/|\s|-]\d+[\.\w]*(\s\[\w+\])?(\sMobile)?)?';
$agent = $_SERVER['HTTP_USER_AGENT'];
$result = 'unknown';
$checks = Array(
'AOL' => 'AOL',
'Avant Browser' => 'Avant Browser',
'MSIE' => 'IE',
'Chrome' => 'Chrome',
'Navigator' => 'Netscape Navigator',
'Iceweasel' => 'Iceweasel',
'SeaMonkey' => 'SeaMonkey',
'Firefox' => 'Firefox',
'Safari' => 'Version Safari',
'Nintendo Wii' => 'Opera',
'Opera' => 'Opera',
'Firebird' => 'Firebird',
'Kazehakase' => 'Kazehakase',
'Iceape' => 'Iceape',
'Phoenix' => 'Phoenix',
'Playstation 3' => 'Playstation 3',
'PSP' => 'Playstation Portable',
'Googlebot' => 'Googlebot',
'msnbot' => 'msnbot-Products msnbot',
'Yahoo! Slurp China' => 'Yahoo! Slurp China',
'Yahoo! Slurp' => 'Yahoo! Slurp',
'Ask Jeeves' => 'Ask Jeeves',
'Cuil' => 'Twiceler',
'Mozilla' => 'Mozilla',
'BlackBerry' => 'BlackBerry'
);
foreach($checks as $key => $check) {
if(preg_match('/(' . $check . ')/', $agent) > 0) {
preg_match('/' . $key . $versmatch . '/', $agent, $matches);
$result = str_replace('-', ' ', str_replace(');', '', str_replace('/', ' ', $matches[0])));
switch($check) {
case 'Safari':
return str_replace($result, 'Version', 'Safari');
break;
case 'Navigator':
return str_replace($result, 'Navigator', 'Netscape');
break;
case 'msnbot':
return str_replace(str_replace($result, 'Products', ''), 'msnbot', 'Windows Live');
break;
case 'Cuil':
return str_replace($result, 'Twiceler', 'Cuil');
break;
case 'Nintendo Wii':
return str_replace($result, 'Opera', 'Nintendo Wii (Opera)');
break;
case 'BlackBerry':
return str_replace($result, 'BlackBerry', 'BlackBerry ');
break;
}
return $result;
}
}
}
Some examples of its return value are 'MSIE 7.0,' 'Firefox 3.0.10,' 'Chrome 2.0.172.33' and 'Safari 525.20.' It may not be the most efficient way to do this, but it gets the job done.
-
Custom Get Browser Function in PHP
2 Comments Posted on September 23rd, 2009
2 Comments
-
orca8767
Apr 17, 2010
Can you make a similar function, for the user's operating system? -
mac
Jun 24, 2010
very cool, mad props and thanks for the amazing breakdown through the various platforms.
Leave a Comment
-
You
Sep 7, 2010