Is it possible for $_SERVER['HTTP_USER_AGENT'] to not be set?

前端 未结 5 1503
眼角桃花
眼角桃花 2020-12-17 08:47

I\'ve just been looking through a website\'s error_log and one of the error\'s that has been logged a few times is:

[21-Jun-2011 12:24:03] PHP Not

相关标签:
5条回答
  • 2020-12-17 09:28

    An example where HTTP_USER_AGENT is undefined is if the request coming from GoDaddy's 404 page handler for your site where you have set the handler to be one of your pages.

    0 讨论(0)
  • 2020-12-17 09:33

    Yes, it's possible, this a HTTP header sent (or not sent) by client, and you should not rely on it. From php manual:

    Contents of the User-Agent: header from the current request, if there is one

    So the correct code would be:

    private function ipad_request() {
        return isset($_SERVER['HTTP_USER_AGENT']) && strstr($_SERVER['HTTP_USER_AGENT'], 'iPad');
    }
    
    0 讨论(0)
  • 2020-12-17 09:35

    PHP docs says:

    'HTTP_USER_AGENT' Contents of the User-Agent: header from the current request, if there is one.

    (relevant part italicised) so it would appear it might not always be set.

    0 讨论(0)
  • 2020-12-17 09:42

    Yes. Any browser or user-agent can choose not to send the User-Agent header. If they do not send that header, $_SERVER['HTTP_USER_AGENT'] won't be set.

    Use isset() to ensure that $_SERVER['HTTP_USER_AGENT'] is set.

    private function ipad_request() {
      if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
    
      return strstr($_SERVER['HTTP_USER_AGENT'], 'iPad') !== false;
    }
    
    0 讨论(0)
  • 2020-12-17 09:48

    Yes, it's possible, but it never happens for a regular request.

    All browsers do send a browser string in the request, so any request that arrives without one comes from some other program. Even all well-behaving bots send a browser string, so you don't have to be concerned about not showing up in search engines either.

    0 讨论(0)
提交回复
热议问题