Skip to content

Instantly share code, notes, and snippets.

@LeonBlade
Created March 5, 2012 21:55
Show Gist options
  • Save LeonBlade/1981421 to your computer and use it in GitHub Desktop.
Save LeonBlade/1981421 to your computer and use it in GitHub Desktop.
PHP for getting browser info
<?php
// get browser data from useragent string for tracking
function _getBrowserInfo() {
// grab the useragent
$ua = $_SERVER['HTTP_USER_AGENT'];
// list of browsers we want to match
$browsers = array(
"firefox",
"msie",
"opera",
"chrome",
"safari",
"mozilla",
"seamonkey",
"konqueror",
"netscape",
"navigator",
"mosaic",
"lynx",
"amaya",
"omniweb",
"avant",
"camino",
"flock",
"aol",
"applewebkit"
);
// list of platforms we want to match
$platforms = array(
"Linux",
"Macintosh",
"Windows",
"iPad",
"iPhone",
"Android"
);
// defaults
$browser = "undetected";
$browser_version = "undetected";
$platform = "undetected";
$platform_version = "undetected";
// match out the middle details part split by ;
preg_match("/\(([^\)]*)\)/", $ua, $matches);
$details = $matches[0];
echo $details;
$details_array = explode(';', $matches[1]);
// loop through the browsers
foreach ($browsers as $b) {
if (preg_match("/\)\s($b)[\/ ]?([\d.]*)/i", $ua, $matches)) {
$browser = $matches[1];
$browser_version = $matches[2];
break;
}
}
// loop through the platforms
foreach ($platforms as $p) {
if (preg_match("/($p)/i", $ua, $matches)) {
$platform = $matches[1];
// switch to OS X if it's available
if ($platform == "Macintosh" && preg_match("/(Mac OS X)/i", $ua, $matches))
$platform = $matches[1];
// switch to Android if it's available
if ($platform == "Android" && preg_match("/(Android)/i", $ua, $matches))
$platform = $matches[1];
// match the version for apple platforms
if (($platform == "Macintosh" || $platform == "Mac OS X" || $platform == "iPad" || $platform == "iPhone") && preg_match("/([\d]+[_\d]{2,})/", $details, $matches))
$platform_version = $matches[1];
// match version for windows
if ($platform == "Windows" && preg_match("/Windows NT ([\d.]*)/", $ua, $matches))
$platform_version = $matches[1];
if (($platform == "Linux" || $platform == "Android") && preg_match("/$platform ([\d.]*)/", $ua, $matches))
$platform_version = $matches[1];
break;
}
}
// create our return array
$return_array = array(
'user_agent' => $ua,
'browser' => $browser,
'browser_version' => $browser_version,
'platform' => $platform,
'platform_version' => $platform_version
);
// return back
return $return_array;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment