百科狗-知识改变命运!
--

get_browser() - php 选项信息函数

梵高1年前 (2023-11-21)阅读数 25#技术干货
文章标签浏览器

get_browser()

(PHP 4, PHP 5, PHP 7)

获取浏览器具有的功能

说明

get_browser([string $user_agent[,bool $return_array= false]]): mixed

通过查找browscap.ini文件中的浏览器信息,尝试检测用户的浏览器所具有的功能。

参数

$user_agent

要分析的用户代理。默认使用HTTP头中User-Agent的值,不过,你可以通过传递该参数改变User-Agent。(比如查找另一个浏览器的信息)

你可以传递一个NULL来忽略该参数。

$return_array

如果设置为TRUE,该函数会返回一个array,而不是object。

返回值

信息会以包含一系列数据的数组或者对象返回。例如:浏览器的主版本号、次版本号和ID字符串;框架、JavaScript、cookies等功能是否支持TRUE/FALSE的值。

cookies的值仅意味着浏览器是否具有接收cookies的功能,不代表用户是否已允许启用cookies。测试的唯一办法,只有通过setcookie()设置一个cookie,刷新页面并检测该cookie的值。

范例

列出所有用户浏览器的信息

get_browser() - php 选项信息函数

以上例程的输出类似于:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3
Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

注释

Note:

为了能让该函数运作,在php.ini中配置的browscap必须指向browscap.ini文件的正确位置。

browscap.ini并未内置在PHP中,不过你可以在这里找到最新的» php_browscap.ini。

browscap.ini包含的诸多浏览器信息依赖于用户更新该数据库。该文件的格式不言自明。

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:
http://php.net/ChangeLog-7.php (search for get_browser())
https://bugs.php.net/bug.php?id=70490
https://github.com/php/php-src/pull/2242
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
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.

Post with more depth here:
https://www.256kilobytes.com/content/show/1922/how-to-parse-a-user-agent-in-php-with-minimal-effort
Since browser detection can be tricky and very slow, I compared a few packages.
http://thadafinser.github.io/UserAgentParserComparison/v5/index.html
https://github.com/sinergi/php-browser-detector
https://github.com/WhichBrowser/Parser-PHP
https://github.com/piwik/device-detector
http://php.net/manual/en/function.get-browser.php
Here are the results:
User Agent: 
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
Sinergi Package
---------------
Chrome 63.0.3239.84 on Windows 10.0
Took 0.0022480487823486 seconds.
---------------
WhichBrowser Package
---------------
Chrome 63 on Windows 10
Took 0.021045207977295 seconds.
---------------
Piwik Package
---------------
Chrome 63.0 on Windows 10
Took 0.079447031021118 seconds.
---------------
get_browser Package
---------------
Chrome 63.0 on Windows 10
Took 0.09611701965332 seconds.
---------------
User Agent: 
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0
Sinergi Package
---------------
Firefox 57.0 on Windows 10.0
Took 0.0023159980773926 seconds.
---------------
WhichBrowser Package
---------------
Firefox 57.0 on Windows 10
Took 0.019663095474243 seconds.
---------------
Piwik Package
---------------
Firefox 57.0 on Windows 10
Took 0.079678058624268 seconds.
---------------
get_browser Package
---------------
Firefox 57.0 on Windows 10
Took 0.02236008644104 seconds.
---------------
The consistent winner (by speed, not necessarily coverage) by far is:
https://github.com/sinergi/php-browser-detector
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.
If you ONLY need a very fast and simple function to detect the browser name (update to May 2016):

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%).
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. 
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).
For those of you using this function to target MSIE, a better idea maybe to use MSIE specific conditional comments. More info: . 
For example to indicate your disregard for users of MSIE 6 or earlier:
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.
As ruudrp had given the code http://php.net/manual/en/function.get-browser.php#101125, I have added code for Internet Explorer 11 
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.
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');
  }
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 CAREFUL WITH THIS FUNCTION!!
This function uses a lot of CPU and RAM on the whole server resources.
Perhaps if you use this function a few times then no problem, but NOT if you use at any page request, or once per session.
Also, this function doesn't work correctly and may returns wrong values, wildcards or empty, so it's not very useful for web statistics.
The best way is to use preg_match for detect browser/platform.
@ruudrp:
you might want to distinguish the OS even further:
(at least for windows that is)
  elseif (preg_match('/windows|win32/i', $u_agent)) {
    $platform = 'Windows';
    if (preg_match('/NT 6.2/i', $u_agent)) { $platform .= ' 8'; }
      elseif (preg_match('/NT 6.3/i', $u_agent)) { $platform .= ' 8.1'; }
      elseif (preg_match('/NT 6.1/i', $u_agent)) { $platform .= ' 7'; }
      elseif (preg_match('/NT 6.0/i', $u_agent)) { $platform .= ' Vista'; }
      elseif (preg_match('/NT 5.1/i', $u_agent)) { $platform .= ' XP'; }
      elseif (preg_match('/NT 5.0/i', $u_agent)) { $platform .= ' 2000'; }
    if (preg_match('/WOW64/i', $u_agent) || preg_match('/x64/i', $u_agent)) { $platform .= ' (x64)'; }
  }
PHP is sensitive to characters outside the range [ A-Za-z0-9_] as values in .ini files. For example
browser=Opera (Bork Version)
causes PHP to complain, as it doesn't like the parentheses.
If you place quotation marks around the values for all keys in the browscap.ini file, you'll save yourself parsing problems. Do this in eg vi with %s/=\(.*\)/="\1"/g
You could of course use PHP itself to fixup the file. Exercise left to the reader.
Here's a quick way to test for a Netscape browser. IE and Konqueror and several others call themselves "Mozilla", but they always qualify it with the word "compatible."
$isns = stristr($HTTP_USER_AGENT, "Mozilla") && (!(stristr($HTTP_USER_AGENT, "compatible")));
This is a simple class to detect the client browser and version using regular expressions. 

example code

result when client using Firefox 3.0.11
firefox 3.0.11
result when client using unknown browser
unknown 0.0.0
 
etc etc
IE has a nasty bug called the Peekaboo bug that affected my website. I found that printing a '_' before the html tag of the webpage gets rid of this nasty bug. Using code inspirated by comment bellow here is the code that detects if a visitor is using internet explorer: 
This is the latest format of the array returned from this call
Array
{
  [browser_name_regex] => ^mozilla/5\.0 (x11; .*; .*linux.*; .*; rv:1\.9\..*) gecko/.* firefox/3\.5.*$
  [browser_name_pattern] => Mozilla/5.0 (X11; *; *Linux*; *; rv:1.9.*) Gecko/* Firefox/3.5*
  [parent] => Firefox 3.5
  [platform] => Linux
  [browser] => Firefox
  [version] => 3.5
  [majorver] => 3
  [minorver] => 5
  [frames] => 1
  [iframes] => 1
  [tables] => 1
  [cookies] => 1
  [javaapplets] => 1
  [javascript] => 1
  [cssversion] => 3
  [supportscss] => 1
  [alpha] => 
  [beta] => 
  [win16] => 
  [win32] => 
  [win64] => 
  [backgroundsounds] => 
  [cdf] => 
  [vbscript] => 
  [activexcontrols] => 
  [isbanned] => 
  [ismobiledevice] => 
  [issyndicationreader] => 
  [crawler] => 
  [aol] => 
  [aolversion] => 0
}
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. 
I stopped trying to detect the browser name and the browser's version, due to the non standard user-agents, is impossible to cover all the possible browsers, and cover only the most used ones is not good.
I only detect the platform, the engine and the version, that cover a lot of possible browsers and let me code based on that, for example, the engine gecko, covers firefox, seamonkey and all the gecko based browsers.
this is a example piece of code taken from my own, is maybe incomplete but as example is good, to detect the engines.

PD: you can add more engines and use an array, I just removed that and put the most popular engines as example, and used elseif instead, this code maybe have errors because is just an example.
I thought this function might be useful to those without access to the php.ini file (such as those on a shared hosting system):

define the location of php_browscap.ini wherever you want
always returns an array, same functionality as get_browser(NULL,true) 
Hope someone finds it useful!
I've just lost a day because of this stupid browser_name_regex property:
e.g. "§^mozilla/5\.0 \(.*windows nt 6\.1.*wow64.*\) gecko/.* firefox/29\.0.*$§"
To replicate the issue and work around bloody '§' character, please below. Whose idea was it to use that character?! 
The only way browscap examines the target browser is through the HTTP_USER_AGENT so there is no way you can determine installed plug-ins. The only way to do that is through client-side JavaScripts.
Your system may have problems parsing browscap.ini if the value fields are not quoted (see bishop's note). This is often true even for the PHP specific version of the published browscap.ini. The sed command below adds quotations to the values:
sed '/^[a-zA-Z0-9].*=[a-zA-Z0-9]/s/=\(.*\)/="\1"/' $inFile > $fixedFile
If you're using a script to fetch the latest browscap.ini, consider adding this operation to the script.
Warning! 
For All Users there is a new website about new 
"Browser Capabilities Project" 
browscap.org
look here : goo.gl/gOPxHp
this is a question about one of the problems have been fixed in the new version.
تحذير!
لكل المستخدمين انه هناك موقع جديد عن مشروع قدرات المتصفح
"Browser Capabilities Project" 
browscap.org
انظر هنا : goo.gl/gOPxHp
هذا هو سؤال عن احد المشاكل التى تم اصلاحُها فى الاصدار الجديد
If the "browscap" directive isn't set in your server's php.ini, then an error warning is shown. Just in case, you could make a call to ini_get() to check if the browscap directive is set before using browser_get(). 
Please keep in mind that you should somehow (for example in session) cache the required results of get_browser() because it really slows thinks down. 
We have experienced that without querying for browser data our scripts would run 120-130% faster. the explanation is that over 200kb long file (browscap.ini) has to be loaded and parsed everytime someone access any page (we need browser results on all pages).
So keep results in session and expect a performance boost.
We are using get_browser() function for useragent Mozilla/4.0 (compatible; MSIE 4.01; Windows NT) the get_browser function is returning as Default Browser and Platform = unknown.
So i added this to my browscap.ini manually:
[Mozilla/4.0 (compatible; MSIE 4.01; Windows NT)]
Parent=IE 4.01
Platform=WinNT
Here is what we do to fix the parsing error messages for php_browscap.ini downloaded from Gary's website. 
After a great deal of research in to how to detect a users browser using php.I found out that the following code below works best so i feel like sharing. 
If you want to use: ceo /a/ mmg5 /./ com 's improved version and STILL detect Google Chrome you need to move CHROME earlier on the list Before Safari otherwise it will be detected as safari.
  $browser_list = 'msie firefox chrome konqueror safari netscape navigator opera mosaic lynx amaya omniweb avant camino flock seamonkey aol mozilla gecko';

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)