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

时间:2009-12-13 06:19:24

标签: php javascript

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

12 个答案:

答案 0 :(得分:15)

我在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;
      }
    }
  }

答案 1 :(得分:7)

以下是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.
    }

答案 2 :(得分:6)

PHP实际上有一个函数,get_browser

答案 3 :(得分:5)

来自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);
?>

答案 4 :(得分:2)

1)99.9%准确的探测器:BrowserDetection.phpExamples

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;
}
?>

答案 5 :(得分:1)

我使用PHP的类 Browser Detect

答案 6 :(得分:1)

在PHP中,我使用$_SERVER['HTTP_USER_AGENT']值并使用regex或stristr攻击它。

答案 7 :(得分:1)

这可能是了解浏览器未使用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);

答案 8 :(得分:1)

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();
}

通过调用

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

答案 9 :(得分:0)

使用JavaScript执行此操作的最简单方法是

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

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

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

这将获取一个URL作为对PHP脚本的查询并转发到该URL。该脚本将被调用如下:

http://your-server/path-to-script/script.php?URL_TO_FORWARD_TO
祝你好运。

答案 10 :(得分:0)

IE 11的引入使得这种方法已经过时,尽管我已将其更新以考虑到这一点。使用JavaScript和特征检测要好得多。当然,有时候你只想完全杀死浏览器和/或必须适应可能禁用JavaScript的用例。

我不知道OP的最终目标,但就我而言,我真正想做的就是反弹Balmer的浏览器。由于正则表达式类似于另一个解决方案导致的误报,我们所拥有的IE 10用户失败了。 (我不知道这个帖子中的正则表达式是否会导致同样的误报,但我确实知道这个页面上的正则与我们的那个不一样。)

我制作了一种不依赖于正则表达式的方法(本身)。我也不想遇到我必须编辑脚本以适应新浏览器的场景,但是,编辑脚本以便将来过期的浏览器是可以接受的。

function obsolete_browser(){
$ua = (isset($_SERVER['HTTP_USER_AGENT']))?$_SERVER['HTTP_USER_AGENT']:'';
$browser = explode(';',$ua);
foreach($browser as &$b){ 
    $b = trim($b); // remove the spaces
    $c = explode('.',$b); // major revision only please
    if($c[0]){ $b = $c[0]; }
}
if(in_array("Trident/7",$browser)){ // IE11
    return false;
} else if(in_array('MSIE 4',$browser) 
|| in_array('MSIE 5',$browser) 
|| in_array('MSIE 6',$browser)  
|| in_array('MSIE 7',$browser) 
//  || in_array('MSIE 8',$browser) // we'll need this soon enough, right?
|| in_array('BOLT/2',$browser) // worst browser ever
){
    return true;
}
return false;
}

答案 11 :(得分:0)

只需 Java脚本即可检测到 浏览器 ,只需调用功能:

    <script>
 function which_browser() {

 //browser_flag --> 0 --> Opera, Chrome, Safari, Firefox
 //browser_flag --> 1 --> Internet Explorer
 var browser_flag = 0;  

 if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) 
{
    alert('Opera --> browser_flag = ' + browser_flag);
}
else if(navigator.userAgent.indexOf("Chrome") != -1 )
{
    alert('Chrome --> browser_flag = ' + browser_flag);
}
else if(navigator.userAgent.indexOf("Safari") != -1)
{
    alert('Safari --> browser_flag = ' + browser_flag);
}
else if(navigator.userAgent.indexOf("Firefox") != -1 ) 
{
     alert('Firefox --> browser_flag = ' + browser_flag);
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
  browser_flag = 1;

  alert('IE --> browser_flag = ' + browser_flag); 
}  
else 
{
   alert('unknown');
}


return browser_flag;
}
</script>

如果IE, browser_flag 获得1, 否则 browser_flag 为0!

当然可调