如何使用 PHP 或 JavaScript 检测浏览器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1895727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:47:39  来源:igfitidea点击:

How can I detect the browser with PHP or JavaScript?

phpjavascript

提问by Web Worm

How can I detect if the user is not using any of the browsers Chrome, Firefox or Internet Explorer using JavaScript or PHP?

如何检测用户是否未使用任何使用 JavaScript 或 PHP 的 Chrome、Firefox 或 Internet Explorer 浏览器?

回答by Fabien Ménager

The best way to do this in JS I found is on Quirksmode. I made one for PHP which should work with common browsers :

我发现在 JS 中执行此操作的最佳方法是使用Quirksmode。我为 PHP 制作了一个,它应该可以与普通浏览器一起使用:

  $browser = array(
    'version'   => '0.0.0',
    'majorver'  => 0,
    'minorver'  => 0,
    'build'     => 0,
    'name'      => 'unknown',
    'useragent' => ''
  );

  $browsers = array(
    'firefox', 'msie', 'opera', 'chrome', 'safari', 'mozilla', 'seamonkey', 'konqueror', 'netscape',
    'gecko', 'navigator', 'mosaic', 'lynx', 'amaya', 'omniweb', 'avant', 'camino', 'flock', 'aol'
  );

  if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $browser['useragent'] = $_SERVER['HTTP_USER_AGENT'];
    $user_agent = strtolower($browser['useragent']);
    foreach($browsers as $_browser) {
      if (preg_match("/($_browser)[\/ ]?([0-9.]*)/", $user_agent, $match)) {
        $browser['name'] = $match[1];
        $browser['version'] = $match[2];
        @list($browser['majorver'], $browser['minorver'], $browser['build']) = explode('.', $browser['version']);
        break;
      }
    }
  }

回答by Zain Shaikh

Here is JavaScript code through which you can easily detect the browser.

这是 JavaScript 代码,您可以通过它轻松检测浏览器。

    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used.
    var Browser = {
        Version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
        Chrome: /chrome/.test(userAgent),
        Safari: /webkit/.test(userAgent),
        Opera: /opera/.test(userAgent),
        IE: /msie/.test(userAgent) && !/opera/.test(userAgent),
        Mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
        Check: function() { alert(userAgent); }
    };

    if (Browser.Chrome || Browser.Mozilla) {
        // Do your stuff for Firefox and Chrome.
    }
    else if (Browser.IE) {
        // Do something related to Internet Explorer.
    }
    else {
        // The browser is Safari, Opera or some other.
    }

回答by txyoji

There is actually a function in PHP for that, get_browser.

PHP 中实际上有一个函数,get_browser

回答by mwafi

PHP code from get_browser()is totally working for me ;)

来自get_browser() 的PHP 代码完全适合我;)

<?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 separately 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);
?>

回答by T.Todua

1) 99.9% accurate detector: BrowserDetection.php(Examples)

1) 99.9% 准确检测器:BrowserDetection.php示例

2) simplest function (but inaccurate for tricking) :

2)最简单的功能(但不准确的欺骗):

<?php
function get_user_browser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];        $ub = '';
    if(preg_match('/MSIE/i',$u_agent))          {   $ub = "ie";     }
    elseif(preg_match('/Firefox/i',$u_agent))   {   $ub = "firefox";    }
    elseif(preg_match('/Safari/i',$u_agent))    {   $ub = "safari"; }
    elseif(preg_match('/Chrome/i',$u_agent))    {   $ub = "chrome"; }
    elseif(preg_match('/Flock/i',$u_agent)) {   $ub = "flock";      }
    elseif(preg_match('/Opera/i',$u_agent)) {   $ub = "opera";      }
  return $ub;
}
?>

回答by vusan

This may be simple way to know that the browser is not using IE, Chrome, or FF

这可能是了解浏览器未使用 IE、Chrome 或 FF 的简单方法

if (navigator.userAgent.indexOf("Chrome") != -1)
    BName = "Chrome";
if (navigator.userAgent.indexOf("Firefox") != -1)
    BName = "Firefox";
if (navigator.userAgent.indexOf("MSIE") != -1)
    BName = "IE";

if(BName=='Chrome' || BName=='Firefox' || BName=='IE') 
    BName="Not other";
else BName="other";
alert(BName);

回答by ianaz

Did this class in JS

在 JS 中做了这个类

function CSystemInfo(){
    var self = this;

    self.nScreenWidth = 0;
    self.nScreenHeight = 0;
    self.sPlatform = "Unknown";
    self.sBrowser = "Unknown";

    var init = function(){
        self.nScreenWidth = screen.width;
        self.nScreenHeight = screen.height;
        self.sPlatform = navigator.platform;
        self.sBrowser = getBrowser();
    }

    var getBrowser = function(){
        var userAgent = navigator.userAgent;
        var version = "UNKNOWN VERSION";

        if (userAgent.toLowerCase().indexOf('msie') > -1) {
            var ieversionreg = /(MSIE ([0-9]{1,2}\.[0-9]{1,2}))/;
            if(ieversionreg.test(userAgent)){
                version = ieversionreg.exec(userAgent)[2];
            }
            return 'Internet Explorer '+version;
        }
        else if (userAgent.toLowerCase().indexOf('firefox') > -1){
            var ffversionreg = /(Firefox\/(.+))/;
            if(ffversionreg.test(userAgent)){
                version = ffversionreg.exec(userAgent)[2];
            }
            return 'Firefox '+version;
        }
        else if (userAgent.toLowerCase().indexOf('chrome') > -1){
            var chromereg = /Chrome\/([0-9]{1,2})/;
            if(chromereg.test(userAgent)){
                version = chromereg.exec(userAgent)[1];
            }
            return 'Google Chrome '+version;
        }
        else return 'Unknown';
    }

    init();
}

instantiate it by calling

通过调用实例化它

var oInfo = new CSystemInfo();
// Retrieve infos
oInfo.sBrowser; // Google Chrome 21

回答by Digital Craft Studios

I use the class Browser Detectfor PHP.

我使用类Browser Detectfor PHP。

回答by Oz.

In PHP I use the $_SERVER['HTTP_USER_AGENT']value and attack it with regex or stristr.

在 PHP 中,我使用该$_SERVER['HTTP_USER_AGENT']值并使用正则表达式或 stristr 对其进行攻击。

回答by bng44270

The simplest way to do it with JavaScript is

用 JavaScript 做到这一点最简单的方法是

<script language="Javascript">
    location.href = 'URL_TO_FORWARD_TO';
</script>

Within the location.href, you could use a PHP variable like so:

在 中location.href,您可以像这样使用 PHP 变量:

<script language="Javascript">
    location.href = '<?php echo $_SERVER['QUERY_STRING']; ?>';
</script>

This would take a URL given as a query to the PHP script and forward to that URL. The script would be called like this:

这将使用作为对 PHP 脚本的查询给出的 URL 并转发到该 URL。该脚本将被调用如下:

http://your-server/path-to-script/script.php?URL_TO_FORWARD_TO

Good luck.

祝你好运。