How to check the user’s browser type and platform
Posted by gladwing in Php Tuesday, 22 August 2006 06:09 No Comments
Sooner or later it might become necessary to write an application that tracks site visitor browser types. Here’s some code to use:
This will output something that looks like one of the following:
Mozilla/4.0 (compatible; MSIE 5.0; Mac_PowerPC)
Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0
Reference
A more complete list of USER AGENT strings (tab delimited)
Next, we’ll build a simple browser checker to check for Internet Explorer (IE), Firefox, Opera and Safari:
$browser_version=$matched[1];
$browser = ‘IE’;
} elseif (preg_match( ‘|Opera ([0-9].[0-9]{1,2})|’,$useragent,$matched)) {
$browser_version=$matched[1];
$browser = ‘Opera’;
} elseif(preg_match(‘|Firefox/([0-9\.]+)|’,$useragent,$matched)) {
$browser_version=$matched[1];
$browser = ‘Firefox’;
} elseif(preg_match(‘|Safari/([0-9\.]+)|’,$useragent,$matched)) {
$browser_version=$matched[1];
$browser = ‘Safari’;
} else {
// browser not recognized!
$browser_version = 0;
$browser= ‘other’;
}
print “browser: $browser $browser_versionâ€;
?>
Now let’s parse out a simple Operating System (OS) checker using the strstr function:
$os=‘Win’;
} else if (strstr($useragent,‘Mac’)) {
$os=‘Mac’;
} else if (strstr($useragent,‘Linux’)) {
$os=‘Linux’;
} else if (strstr($useragent,‘Unix’)) {
$os=‘Unix’;
} else {
$os=‘Other’;
}
print “OS: $osâ€;
?>
Leave a Reply