Skip to content

Instantly share code, notes, and snippets.

@ricardosiri68
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save ricardosiri68/1d4a5af08b27acb02d4e to your computer and use it in GitHub Desktop.

Select an option

Save ricardosiri68/1d4a5af08b27acb02d4e to your computer and use it in GitHub Desktop.
<?php require_once 'user_agent.php'; ?>
<!-- Now try it. -->
<?php $userAgent = new UserAgent($_SERVER['HTTP_USER_AGENT']); ?>
<?php $ua = $userAgent->getBrowser(); ?>
<p>
<b>Your Browser:</b>
</p>
<?=$ua['name']?> <?=$ua['version']?> on <?=$ua['platform']?>
<?php
class UserAgent
{
public $bname = 'Unknown';
public $platform = 'Unknown';
public $version = "";
public $browser_matches = [
['/MSIE/i', "MSIE", 'Internet Explorer'],
['/Firefox/i', "Firefox", 'Mozilla Firefox'],
['/Chrome/i', "Chrome", 'Google Chrome'],
['/Safari/i', "Safari", 'Apple Safari'],
['/Opera/i', 'Opera', 'Opera'],
['/Netscape/i', 'Netscape', 'Netscape']
];
public function __construct($u_agent)
{
$this->u_agent = $u_agent;
}
public function getBrowser()
{
foreach ($this->browser_matches as $browser_match) {
$regex = $browser_match[0];
if (preg_match($regex, $this->u_agent)) {
$this->bname = $browser_match[2];
$this->ub = $browser_match[1];
break;
}
}
if ( preg_match('/MSIE/i', $this->u_agent) &&
! preg_match('/Opera/i', $this->u_agent)) {
$this->bname = 'Internet Explorer';
$this->ub = "MSIE";
}
return array(
'userAgent' => $this->u_agent,
'name' => $this->bname,
'version' => $this->getVersion(),
'platform' => $this->getPlatform(),
'pattern' => $this->getPattern()
);
}
public function getPlatform()
{
//First get the platform?
if (preg_match('/linux/i', $this->u_agent)) {
$platform = 'linux';
} elseif (preg_match('/macintosh|mac os x/i', $this->u_agent)) {
$platform = 'mac';
} elseif (preg_match('/windows|win32/i', $this->u_agent)) {
$platform = 'windows';
}
return $platform;
}
public function getPattern()
{
$known = array('Version', $this->ub, 'other');
return '#(?<browser>' .
join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
}
public function getVersion()
{
$matches = [];
// Next get the name of the useragent yes separately and for good reason.
// Finally get the correct version number.
$pattern = $this->getPattern();
if (!preg_match_all($pattern, $this->u_agent, $matches)) {
// we have no matching number just continue
continue;
}
// See how many we have.
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if ( strripos($this->u_agent, "version")
< strripos($this->u_agent, $this->ub)) {
$version = $matches['version'][0];
} else {
$version = $matches['version'][1];
}
} else {
$version = $matches['version'][0];
}
return ($version == null || $version == "") ? "?":$version;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment