Skip to content

Instantly share code, notes, and snippets.

@themaoci
Created September 14, 2020 10:37
Show Gist options
  • Save themaoci/6b67bd684351d54db8bc6887677b649f to your computer and use it in GitHub Desktop.
Save themaoci/6b67bd684351d54db8bc6887677b649f to your computer and use it in GitHub Desktop.
Detecting browser and os versions using useragent.
<?php
function getBrowserData()
{
/* Made By TheMaoci */
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version= "";
$osArray = array(
'/windows nt 10.0/i' => 'Windows 10',
'/windows nt 6.4/i' => 'Windows 9 ?lol',
'/windows nt 6.3/i' => 'Windows 8.1',
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
$browserArray = array(
'/Opera/i' => array('Opera' ,"Opera"),
'/MSIE/i' => array('Internet Explorer',"MSIE"),
'/Firefox/i' => array('Mozilla Firefox' ,"Firefox"),
'/Chrome/i' => array('Google Chrome' ,"Chrome"),
'/Safari/i' => array('Apple Safari' ,"Safari"),
'/Netscape/i' => array('Netscape' ,"Netscape"),
);
foreach ($osArray as $regex => $value)
if (preg_match($regex, $u_agent)) {
$platform = $value;
break;
}
foreach ($browserArray as $regex => $value)
if (preg_match($regex, $u_agent)) {
$bname = $value[0];
$ub = $value[1];
break;
}
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}
$i = count($matches['browser']);
if ($i != 1) {
if (strripos($u_agent,"Version") < strripos($u_agent,$ub))
$version= $matches['version'][0];
else
$version= $matches['version'][1];
}
else
$version= $matches['version'][0];
if ($version==null || $version=="") {$version="?";}
return array(
'ua' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}
print_r(getBrowserData());
/* returned value:
Array
(
[ua] => Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0
[name] => Mozilla Firefox
[version] => 80.0
[platform] => Windows 10
[pattern] => #(?
)
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment