note 92310 deleted from function.get-browser by cmb
| From: | cmb@php.net | Date: | Sun, 23 Feb 2020 08:58:37 +0000 |
| Subject: | note 92310 deleted from function.get-browser by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-214201@lists.php.net to get a copy of this message | ||
Note Submitter: robert at broofa dot com
----
If you're just finding this API, note that you may want to use a lighter-weight
browser detection script. get_browser() requires the "browscap.ini" file,
which is 300KB+. Loading and processing this file will likely impact script
performance. Although it surely provides excellent detection results, in most
cases a much simpler method can be just as effective. This is why so many
previous commenters have provided alternate implementations.
Here's the solution I ended up using, which I've tested on the agents listed at
http://whatsmyuseragent.com/CommonUserAgents.asp
It has the advantage of being
compact and reasonably easy to extend (just add entries to the $known array
defined at the top). It should be fairly performant as well, since it doesn't
do any iteratoin or recursion.
<?php
function browser_info($agent=null) {
// Declare known browsers to look for
$known = array('msie', 'firefox', 'safari', 'webkit',
'opera', 'netscape',
'konqueror', 'gecko');
// 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']);
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';
// Find all phrases (or return empty array if none found)
if (!preg_match_all($pattern, $agent, $matches)) return array();
// 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($matches['browser'][$i] => $matches['version'][$i]);
}
?>
This returns an array with the detected browser as the key, and the version as
the value, and also sets 'browser' and 'version' keys. For example on Firefox
3.5:
<?php
$ua = browser_info();
print_r($ua);
/* Yields ...
Array
(
[firefox] => 3.5
[browser] => firefox
[version] => 3.5
)
*/
// Various browser tests you can do with the returned array ...
if ($ua['firefox']) ... // true
if ($ua['firefox'] > 3) ... // true
if ($ua['firefox'] > 4) ... // false
if ($ua['browser'] == 'firefox') ... // true
if ($ua['version'] > 3.5) ... // true
if ($ua['msie']) ... // false ('msie' key not defined)
if ($ua['opera'] > 3) ... // false ('opera' key not defined)
if ($ua['safari'] < 3) ... // false also ('safari' key not defined)
?>