以下代码验证访问该站点的用户代理,但是我收到错误.需要更新以适应没有设置用户代理的情况?
错误
PHP注意:未定义的索引:第7行的Utils.PHP中的HTTP_USER_AGENT
码
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 ); }
User-Agent头是可选的.防火墙可能会过滤它,或者人们可能会配置他们的客户端来省略它.只需使用isset()检查是否存在.或者甚至更好,使用!empty()作为一个空标题也不会有用:
原文链接:https://www.f2er.com/php/140004.htmlpublic static function detectBrowser() { if(empty($_SERVER['HTTP_USER_AGENT'])) { return array( 'name' => 'unrecognized','version' => 'unknown','platform' => 'unrecognized','userAgent' => '' ); } // your old code here }
然而,由于您的所有代码似乎在空字符串中正常工作,并且还会生成“未知”值,您可以简单地更改以下行:
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
喜欢这个:
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';