PHP Undefined index: HTTP_USER_AGENT

前端 未结 2 1787
忘了有多久
忘了有多久 2020-12-16 10:56

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

相关标签:
2条回答
  • 2020-12-16 11:14

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

    like this:

    $userAgent = isset($_SERVER['HTTP_USER_AGENT'])
                   ? strtolower($_SERVER['HTTP_USER_AGENT'])
                   : '';
    
    0 讨论(0)
  • 2020-12-16 11:20

    use isset:

    if( !isset( $_SERVER['HTTP_USER_AGENT'])){
        $name = "none";
    }else{
         $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
    
        if (preg_match('/opera/', $userAgent)) {
            $name = 'opera';
        } [... yourcode ...]
    }
    
    0 讨论(0)
提交回复
热议问题