如何使用 PHP 将“Google Chrome”检测为用户代理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3047894/
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-25 08:31:19  来源:igfitidea点击:

How to detect "Google Chrome" as the user-agent using PHP?

phpregexgoogle-chromeuser-agentbrowser-detection

提问by Xubin

I'm interested to know whether the user-agent is "Chrome" at the server end using PHP. Is there a reliable regular expression for parsing out the user-agent string from the request header?

我很想知道用户代理是否是使用 PHP 的服务器端的“Chrome”。是否有可靠的正则表达式来解析请求标头中的用户代理字符串?

回答by BoltClock

At this point, too many browsers are pretending to be Chrome in order to ride on its popularity as well as combating abuse of browser detection for a simple match for "Chrome" to be effective anymore. I would recommend feature detection going forward, but Chrome (and WebKit/Blink in general) is notorious for lying to feature detection mechanisms as well, so even that isn't as great as it's cracked up to be anymore either.

在这一点上,太多的浏览器假装是 Chrome,以利用其受欢迎程度以及打击浏览器检测的滥用,使“Chrome”的简单匹配不再有效。我建议继续进行特征检测,但 Chrome(以及一般的 WebKit/Blink)也因对特征检测机制撒谎而臭名昭著,因此即使这样也不再像人们所说的那样好。

I can only recommend staying on top of things by comparing its known UA strings with those of other browsers through third-party sites, and creating patterns from there. How you do this depends entirely on the strings themselves. Just keep in mind that due to the nature of browsers, and UA strings, there can never be a "reliable" regular expression for matching them.

我只能建议通过将其已知的 UA 字符串与通过第三方站点的其他浏览器的字符串进行比较,并从那里创建模式来保持领先地位。如何做到这一点完全取决于字符串本身。请记住,由于浏览器和 UA 字符串的性质,永远不可能有“可靠”的正则表达式来匹配它们。

In PHP, the relevant server var is $_SERVER['HTTP_USER_AGENT'].

在 PHP 中,相关的服务器变量是$_SERVER['HTTP_USER_AGENT'].

回答by Adam

Worth mentioning that if you also want to include Chrome for iOS, you will need to match against "CriOS" as well:

值得一提的是,如果您还想包含适用于 iOS 的 Chrome,您还需要匹配“CriOS”:

if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false
 || strpos($_SERVER['HTTP_USER_AGENT'], 'CriOS') !== false) {
    // User agent is Google Chrome
}

回答by Leia

Building on @Adams answer, more accurately detecting Google Chrome by exclude some browsers with "Chrome" in the user agent string using useragentstring.comand udger.com:

基于@Adams 的回答,通过使用useragentstring.comudger.com在用户代理字符串中排除一些带有“Chrome”的浏览器来更准确地检测 Google Chrome :

if(preg_match('/(Chrome|CriOS)\//i',$_SERVER['HTTP_USER_AGENT'])
 && !preg_match('/(Aviator|ChromePlus|coc_|Dragon|Edge|Flock|Iron|Kinza|Maxthon|MxNitro|Nichrome|OPR|Perk|Rockmelt|Seznam|Sleipnir|Spark|UBrowser|Vivaldi|WebExplorer|YaBrowser)/i',$_SERVER['HTTP_USER_AGENT'])){
    // Browser might be Google Chrome
}