28

以下代码验证了访问该站点的用户代理,但是我收到了错误消息。我需要更新什么以适应没有设置用户代理的场景?

ERROR PHP Notice: Undefined index: HTTP_USER_AGENT in Utils.php on line 7

代码

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

2 回答 2

59

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
}

但是,由于您的所有代码似乎都可以在空字符串上正常工作并且还会产生“未知”值,因此您可以简单地更改以下行:

$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);

像这样:

$userAgent = isset($_SERVER['HTTP_USER_AGENT'])
               ? strtolower($_SERVER['HTTP_USER_AGENT'])
               : '';
于 2013-01-02T23:26:27.980 回答
9

使用 isset:

if( !isset( $_SERVER['HTTP_USER_AGENT'])){
    $name = "none";
}else{
     $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);

    if (preg_match('/opera/', $userAgent)) {
        $name = 'opera';
    } [... yourcode ...]
}
于 2013-01-02T23:26:19.313 回答