As of PHP 7.0.15 and 7.1.1 and higher, get_browser() now performs much better - reportedly 100x faster. The Changelog, bug description, and solution are here:
Anonymous ¶9 years ago
This function is too slow for todays needs.
If you need browser / device / operating system detection, please try one of listed packages here: https://github.com/ThaDafinser/UserAgentParser
If you ONLY need a very fast and simple function to detect the browser name (update to May 2016):
<?php
function get_browser_name($user_agent)
{
if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
elseif (strpos($user_agent, 'Edge')) return 'Edge';
elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
elseif (strpos($user_agent, 'Safari')) return 'Safari';
elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
return 'Other';
}
/ Usage:
echo get_browser_name($_SERVER['HTTP_USER_AGENT']);
?>
This function also resolves the trouble with Edge (that contains in the user agent the string "Safari" and "Chrome"), with Chrome (contains the string "Safari") and IE11 (that do not contains 'MSIE' like all other IE versions).
Note that "strpos" is the fastest function to check a string (far better than "preg_match") and Opera + Edge + Chrome + Safari + Firefox + Internet Explorer are the most used browsers today (over 97%).
Since browser detection can be tricky and very slow, I compared a few packages.
https://github.com/piwik/device-detector
https://github.com/sinergi/php-browser-detector
To my surprise I found that none of the get_browser alternatives output the correct name / version combination that I was looking for using Opera or Chrome. They either give the wrong name eg Safari when in fact it should be Chrome and if the ua string includes a version number as with the latest versions of Chrome and Opera the wrong number is reported. So I took bits and pieces from the various examples and combined them and added a check for version.
<?php
function getBrowser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version= "";
/First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
/ Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
{
$bname = 'Internet Explorer';
$ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$u_agent))
{
$bname = 'Mozilla Firefox';
$ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$u_agent))
{
$bname = 'Google Chrome';
$ub = "Chrome";
}
elseif(preg_match('/Safari/i',$u_agent))
{
$bname = 'Apple Safari';
$ub = "Safari";
}
elseif(preg_match('/Opera/i',$u_agent))
{
$bname = 'Opera';
$ub = "Opera";
}
elseif(preg_match('/Netscape/i',$u_agent))
{
$bname = 'Netscape';
$ub = "Netscape";
}
/ finally get the correct version number
$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
}
/ 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($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
}
else {
$version= $matches['version'][1];
}
}
else {
$version= $matches['version'][0];
}
/ check if we have a number
if ($version==null || $version=="") {$version="?";}
return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}
/ now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>
Follow up to Francesco R's post from 2016.
His function works for most human traffic; added a few lines to cover the most common bot traffic. Also fixed issue with function failing to detect strings at position 0 due to strpos behavior.
<?php
/ Function written and tested December, 2018
function get_browser_name($user_agent)
{
/ Make case insensitive.
$t = strtolower($user_agent);
/ If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space.
/ "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE."
/ https://www.256kilobytes.com/content/show/1922/how-to-parse-a-user-agent-in-php-with-minimal-effort
Good news! The latest version of PHP has a performance fix for this function. It's reportedly now 100x faster. See the ChangeLog for specifics.
PHP cron script to automatically update browscap.ini. It compares version numbers to determine if update is needed:
<?php
$eol="\r\n"; /set end of line - cron
$fileurl = "https://browscap.org/version-number";
$file = "/path/to/browscap.ini";
/Find current version
$fp = fopen($file, "r+");
while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
if(strpos($line,"Version=")===0) {
list($temp, $curver) = explode("=",$line);
break;
}
}
fclose($fp);
echo("Current browscap.ini file version: " . $curver);
/Get browscap.org current version
$newver = file_get_contents($verurl);
echo($eol . "New browscap.ini file version: " . $newver);
/Update if new version available
if($newver > $curver) {
if(file_put_contents($file, file_get_contents($fileurl))) {
echo($eol . "browscap.ini has been updated!");
}
else {
echo($eol . "browscap.ini update failed!");
}
}
else {
echo($eol . "browscap.ini is up to date!");
}
echo($eol . "End of Cron job." . $eol");
?>
To automatically update your browscap.ini file on linux servers, you can use this simple shell script:
wget -O /etc/browscap.ini "http://browscap.org/stream?q=Full_PHP_BrowsCapINI"
chmod 664 /etc/browscap.ini
You can put it in the weekly cron job folder usually located in /etc/cron.weekly just don't forget to make the script executable (chmod 775 scriptname).
As ruudrp had given the code http://php.net/manual/en/function.get-browser.php#101125, I have added code for Internet Explorer 11
<?php
function getBrowser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version= "";
/First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
/ Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
{
$bname = 'Internet Explorer';
$ub = "MSIE";
}
elseif(preg_match('/Trident/i',$u_agent))
{ / this condition is for IE11
$bname = 'Internet Explorer';
$ub = "rv";
}
elseif(preg_match('/Firefox/i',$u_agent))
{
$bname = 'Mozilla Firefox';
$ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$u_agent))
{
$bname = 'Google Chrome';
$ub = "Chrome";
}
elseif(preg_match('/Safari/i',$u_agent))
{
$bname = 'Apple Safari';
$ub = "Safari";
}
elseif(preg_match('/Opera/i',$u_agent))
{
$bname = 'Opera';
$ub = "Opera";
}
elseif(preg_match('/Netscape/i',$u_agent))
{
$bname = 'Netscape';
$ub = "Netscape";
}
/ finally get the correct version number
/ Added "|:"
$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
}
/ 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($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
}
else {
$version= $matches['version'][1];
}
}
else {
$version= $matches['version'][0];
}
/ check if we have a number
if ($version==null || $version=="") {$version="?";}
return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}
/ now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>
Be aware that loading php_browscap.ini via the browscap php.ini setting may consume a non-trivial amount of memory. Current versions are several MB in size (even the “lite” one) and can eat tens of MB of RAM in each PHP process. This happens even if you never call get_browser() since php_browscap.ini is loaded when PHP is starting up.
Make sure to leave the browscap php.ini setting empty if you don’t use get_browser() – maybe you only call it only from PHP Web pages, but not from PHP CLI code.
I’d recommend comparing your processes’ memory consumption with and without php_browscap.ini being loaded. If necesseray, consider creating your own stripped-down copy of php_browscap.ini with just the browsers that are important to you.
You should not rely on just this for cross-browser compatibility issues. Good practice would be to include HTML if-statements for IE stylesheets as well as dynamically checking the browser type.
Be aware of the fact that this function shows what a specific browser might be able to show, but NOT what the user has turned on/off.
So maybe this function tells you that the browser is abel to to javascript even when javascript is turned off by the user.
Be careful about using homegrown versions of these.
For example Francesco R's highly rated [ https://www.php.net/manual/en/function.get-browser.php#119332 ] version is no longer correct with Edge:
Current Edge is reporting a string similar to:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0
Note the "Edg/xxx" instead of "Edge"
While it is trivial to update his code to:
<?php
function get_browser_name($user_agent)
{
if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
elseif (strpos($user_agent, 'Edg')) return 'Edge';
elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
elseif (strpos($user_agent, 'Safari')) return 'Safari';
elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
return 'Other';
}
?>
You never know when a value might change in the future.
Be careful if you use the "Full" Browscap INI file in your php.ini config: I wondered why each Apache thread took 350MB RAM on my server until I changed the "Full" version by the "Lite" one (45MB to 0.7MB)
Now, each thread takes only 16MB...
So if it is enough for you, use the Lite version!
To complete Francesco R, I added the version of the navigator :
function getNavigateur($user_agent)
{
if(empty($user_agent)) {
return array('nav' => 'NC', 'name' => 'NC', 'version' => 'NC');
}
$content_nav['name'] = 'Unknown';
if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) {
$content_nav['name'] = 'Opera';
if (strpos($user_agent, 'OPR/')) {
$content_nav['reel_name'] = 'OPR/';
} else {
$content_nav['reel_name'] = 'Opera';
}
}
elseif (strpos($user_agent, 'Edge')) {
$content_nav['name'] = $content_nav['reel_name'] = 'Edge';
}
elseif (strpos($user_agent, 'Chrome')) $content_nav['name'] = $content_nav['reel_name'] = 'Chrome';
elseif (strpos($user_agent, 'Safari')) $content_nav['name'] = $content_nav['reel_name'] = 'Safari';
elseif (strpos($user_agent, 'Firefox')) $content_nav['name'] = $content_nav['reel_name'] = 'Firefox';
elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7') || strpos($user_agent, 'Trident/7.0; rv:')) {
$content_nav['name'] = 'Internet Explorer';
if (strpos($user_agent, 'Trident/7.0; rv:')) {
$content_nav['reel_name'] = 'Trident/7.0; rv:';
} elseif (strpos($user_agent, 'Trident/7')) {
$content_nav['reel_name'] = 'Trident/7';
} else {
$content_nav['reel_name'] = 'Opera';
}
}
$pattern = '#' . $content_nav['reel_name'] . '\/*([0-9\.]*)#';
$matches = array();
if(preg_match($pattern, $user_agent, $matches)) {
$content_nav['version'] = $matches[1];
return $content_nav;
}
return array('name' => $content_nav['name'], 'version' => 'Inconnu');
}