note 100203 deleted from function.get-browser by danbrown
| From: | danbrown@php.net | Date: | Thu, 30 Sep 2010 20:11:02 +0000 |
| Subject: | note 100203 deleted from function.get-browser by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-172857@lists.php.net to get a copy of this message | ||
Note Submitter: ravi dot rajendra at gmail dot com
----
Added few lines of code to the Robert's browser_info() function to get the full OS details
from the $_SERVER['HTTP_USER_AGENT'].
Made changes to the parser to make it work for google chrome and MAC user agents. Currently, this
code is good for the user agents listed in http://www.peacemax.com/11/php/user-agents/
<?php
/**
*
* Gets the OS, browser name and browser version of the client
* @param $agent
*/
public static function getClientBrowserInfo($agent=null) {
// Declare known browsers to look for
$known = array('msie', 'firefox','chrome', 'safari',
'webkit', 'opera', 'netscape',
'konqueror', 'gecko', 'googlebot', 'googlebot-image',
'ask', 'msnbot-products');
$os_known = array('linux','mac','win');
// Clean up agent and build regex that matches phrases for known browsers
// (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor
// version numbers. E.g. "2.0.0.6" is parsed as simply "2.0"
$agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']);
// Use the User Agent String to get the OS full details.
$os = '';
if(preg_match('#\(.*?(['.join('|',$os_known).'].*?)\)#i', $agent,
$os_matches) != 0)
{
$os = $os_matches[1];
}
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#i';
// Find all phrases (or return empty array if none found)
if (!preg_match_all($pattern, $agent, $matches)) return
array('name'=>'','version'=>'','os' =>
$os);
//A tweak for chrome in Mac as this is giving safari as the last match.
if($key = array_search('chrome', $matches['browser']))
return array('name'=> $matches['browser'][$key], 'version'
=> $matches['version'][$key], 'os'=>$os );
// Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
// Opera 7,8 have a MSIE phrase), use the last one found (the right-most one
// in the UA). That's usually the most correct.
$i = count($matches['browser'])-1;
return array('name'=> $matches['browser'][$i], 'version' =>
$matches['version'][$i], 'os'=>$os);
}
?>
Hope this will be useful. I have used this for database log of the user details when he registers,
logs-in and logs-off.