views:

78

answers:

3

I'm using $_SERVER['HTTP_USER_AGENT'] to detect user's browser. When I run the var_dump on my localhost on IE8 it returns: ...compatible; MSIE 8.0; ... But when I upload it to my host (godaddy), I get: ...compatible; MSIE 7.0; ...

What's the problem?

A: 

Try this and see what happens.

Neb
A: 

Check for the word TRIDENT in the string. The compatibility-thing is ie in compatibility-mode. Google it if you want to know what it means. However, the term trident is only ie8+.

Edit: Also, you can set a headder/meta-tag to force ie8-mode (no compatibility). However, this will probably not take effect before the second request. Google that too.

Alxandr
if preg_match('/Trident\/4\.0;/i', $_SERVER['HTTP_USER_AGENT']) > 0 than it's IE8 :)
svovaf
Haha. My php is getting rusty, but had the same problem in asp :-P
Alxandr
+3  A: 

I'm using $_SERVER['HTTP_USER_AGENT'] to detect user's browser

Yeah, that's the problem. Don't do that.

User-Agent string-hacking is a losing game. There are any number of odd cases that are likely to confuse your scripts.

This is one of them: IE8, when defaulting to Compatibility Mode, pretends to be IE7. You can detect this case by the presence of Trident/... in the string, but of course like all string-hacking ‘solutions’ this'll go wrong if that string happens to be present for other reasons, which it might be given that any application can stick arbitrary strings to the end of IE's User-Agent header, and indeed given that browsers regularly lie about who they are, and intermediaries may change or remove the header.

Also by doing browser-sniffing at the server-side, you are making your HTTP responses depend on the browser viewing them, which means that proxy caches will serve the wrong page to the wrong browser unless you include the proper Vary header. But if you do that, you break caching in IE.

Server-side UA sniffing is a horror that you should only ever use as a last resort if it really isn't possible to use any other technique. For the usual case of showing different content to particular versions of IE, you are much better off with conditional comments.

bobince
+1 to hell with daily vote limit :)
galambalazs