Anonymous Girl
Anonymous Girl

Reputation: 642

Undefined index: HTTP_USER_AGENT in Laravel for few users

I am using laravel framework to check if it mobile using helper.php, but i get sometimes errors in laravel.log with: Undefined index: HTTP_USER_AGENT

My Code helper.php code:

    public static function isMobile() 
{
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

view/ code:

@if(App\Helper::isMobile())
    <p>it is mobile</p>
@endif

Upvotes: 0

Views: 912

Answers (1)

John Lobo
John Lobo

Reputation: 15319

As a other question answer by @thiefmaster

Ref:PHP Undefined index: HTTP_USER_AGENT

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 isMobile() { 
     $userAgent=null; 
      if(isset($_SERVER["HTTP_USER_AGENT"])){ 
    $userAgent=preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]); 
    } 
  return $userAgent; 
} 

or you can do following

 public static function isMobile() { 
         $userAgent=null; 
          if(isset(request()->userAgent())){ 
        $userAgent=preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i",request()->userAgent()); 
        } 
      return $userAgent; 
    } 

Also i suggest you to use agent library https://github.com/jenssegers/agent

Upvotes: 2

Related Questions