PHP未定义索引:HTTP_USER_AGENT [英] PHP Undefined index: HTTP_USER_AGENT

查看:744
本文介绍了PHP未定义索引:HTTP_USER_AGENT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码验证了访问网站的用户代理,但是我遇到了错误.我需要更新什么以适应未设置用户代理的情况?

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?

错误 PHP注意:未定义的索引:第7行的Utils.php中的HTTP_USER_AGENT

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

推荐答案

User-Agent标头是可选的.防火墙可能会对其进行过滤,或者人们可能会将其客户端配置为忽略它.只需使用isset()检查是否存在.甚至更好,请使用!empty(),因为空标头也无用:

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:

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']);

像这样:

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

这篇关于PHP未定义索引:HTTP_USER_AGENT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆