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

Martin Bean picture Martin Bean · Jun 24, 2011 · Viewed 21.1k times · Source

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 Notice: Undefined index: HTTP_USER_AGENT in /home/ukevents/public_html/lib/toro.php on line 130

The line this pertains to in toro.php is:

private function ipad_request() {
    return strstr($_SERVER['HTTP_USER_AGENT'], 'iPad');
}

Is it possible for $_SERVER['HTTP_USER_AGENT'] to not be set by a HTTP request?

Answer

Maxim Krizhanovsky picture Maxim Krizhanovsky · Jun 24, 2011

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