PHP 未定义索引:HTTP_USER_AGENT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14130830/
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
PHP Undefined index: HTTP_USER_AGENT
提问by PeanutsMonkey
The following code validates the user agent accessing the site however I am getting the error. What do I need to update to accommodate scenarios where there is no user agent being set?
以下代码验证访问该站点的用户代理,但是我收到错误消息。我需要更新什么以适应没有设置用户代理的场景?
ERRORPHP Notice: Undefined index: HTTP_USER_AGENT in Utils.php on line 7
ERRORPHP Notice: Undefined index: HTTP_USER_AGENT in Utils.php on line 7
CODE
代码
public static function detectBrowser()
{
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('/opera/', $userAgent)) {
$name = 'opera';
}
elseif (preg_match('/webkit/', $userAgent)) {
$name = 'safari';
}
elseif (preg_match('/msie/', $userAgent)) {
$name = 'msie';
}
elseif (preg_match('/mozilla/', $userAgent) && !preg_match('/compatible/', $userAgent)) {
$name = 'mozilla';
}
else {
$name = 'unrecognized';
}
if (preg_match('/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/', $userAgent, $matches)) {
$version = $matches[1];
}
else {
$version = 'unknown';
}
if (preg_match('/linux/', $userAgent)) {
$platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/', $userAgent)) {
$platform = 'mac';
}
elseif (preg_match('/windows|win32/', $userAgent)) {
$platform = 'windows';
}
else {
$platform = 'unrecognized';
}
return array(
'name' => $name,
'version' => $version,
'platform' => $platform,
'userAgent' => $userAgent
);
}
回答by ThiefMaster
The User-Agent header is optional. Firewalls may filter it or people may configure their clients to omit it. Simply check using isset()if it exists. Or even better, use !empty()as an empty header won't be useful either:
User-Agent 标头是可选的。防火墙可能会过滤它,或者人们可能会将其客户端配置为忽略它。只需检查 usingisset()是否存在。或者更好的是,!empty()用作空标题也没有用:
public static function detectBrowser() {
if(empty($_SERVER['HTTP_USER_AGENT'])) {
return array(
'name' => 'unrecognized',
'version' => 'unknown',
'platform' => 'unrecognized',
'userAgent' => ''
);
}
// your old code here
}
However, since all of your code seems to work fine on an empty string and also yield the "unknown" values you could simply change the following line:
但是,由于您的所有代码似乎在空字符串上都可以正常工作,并且还会产生“未知”值,因此您只需更改以下行即可:
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
like this:
像这样:
$userAgent = isset($_SERVER['HTTP_USER_AGENT'])
? strtolower($_SERVER['HTTP_USER_AGENT'])
: '';
回答by Green Black
use isset:
使用 isset:
if( !isset( $_SERVER['HTTP_USER_AGENT'])){
$name = "none";
}else{
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('/opera/', $userAgent)) {
$name = 'opera';
} [... yourcode ...]
}

