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

你离开我真会死。 提交于 2019-11-27 03:48:39

问题


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?


回答1:


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.

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.

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




回答2:


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

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



回答3:


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

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
}


来源:https://stackoverflow.com/questions/3047894/how-to-detect-google-chrome-as-the-user-agent-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!