views:

518

answers:

12

I run across this constantly, render some HTML if the browser is IE and some other if FFX (or mac, opera, etc).

This is what I use (pardon the missing underscores)

if(ereg("msie", strtolower($SERVER['HTTPUSERAGENT']))) { }

Anyone know a shorter way? (I use PHP but, just for the heck of it, i'd love to see non-PHP code as well who knows maybe there's some lisp "browser ie" syntax)

/mp

+1  A: 

From the horse's mouth (it shouldn't be too hard to translate this to PHP):

http://msdn.microsoft.com/en-us/library/ms537509.aspx

Stu
+5  A: 

Prototype, the javascript library, does it like so:

var IE = !!(window.attachEvent && !window.opera);

If you need this in PHP, then I'm little help.

EndangeredMassa
A: 

In .NET, you could do something like:

IF Request.Browser.IsBrowser("IE") THEN ...

EndangeredMassa
+1  A: 

@Sean and @Stu,

Those .NET examples are not going to be of much use to non-.NET developers since they are using methods from ASP.NET. Underneath, the methods are inspecting the httpuseragent HTTP header which is the way to do browser sniffing on the server.

Browser sniffing on the server usually isn't the best solution. Ideally, you would send the same HTML to IE, FireFox, Safari, Opera, etc., and rely on CSS and conditional comments to render it appropriately. Use a JavaScript library like jQuery, YUI, Prototype, etc. to make your js cross-browser.

Where server browser sniffing can work well, is in showing totally different markup for iPhones and other mobile devices.

Lance Fisher
+1  A: 

You should be more specific about the situation you're using this for; it sounds to me like this isn't the optimal way of doing whatever it is you're doing.

Andrew G. Johnson
A: 

@Lance: True, but the asker said that non-PHP methods were fine. I provided a Javascript answer and a .NET answer.

EndangeredMassa
A: 

Using jQuery,

I just use jQuery.browser.msie which is a boolean.

T.

tomdemuyt
I think this has been depreciated in 1.3
alex
+2  A: 

browser detection is bad you should probably find another way to do whatever it is you're trying to do

Marc Gear
scunliffe
In those cases, you can still user feature detection over browser detection.
EndangeredMassa
+1  A: 

pure Javascript. 11 characters.

m//@cc_on=1

alert(m ? "Internet explorer" : "Not internet explorer");
nickf
+1  A: 

for a pure javascript approach.

window.external;//is an object in IE
scunliffe
A: 

another way is:

!!document.all
annakata
A: 

I realize your post is about server-side detection, but this is too cool not to share.

Gareth Heyes wrote a blog post with a bunch of cool hacky ways to detect the browser in as little bytes as possible. His method for detecting IE is:

IE='\v'=='v'

This works on all versions of IE including 8. As it turns out, this is not the shortest way to tell. You can shorten it to:

IE=!+"\v1"

Code golfing at its best.

itsadok