tags:

views:

263

answers:

4

How do I get the browser name using PHP? I thought this would be straightforward? All I need to do is differentiate between IE and Firefox.

+6  A: 

$_SERVER['HTTP_USER_AGENT']

Sergey Kuznetsov
+4  A: 

check the docs, always

ghostdog74
I had been working in PHP for years but I did not know that. (I don't really needed it either.)
Notinlist
@ghost - This would be a great answer if it weren't just RTFM with a link.
antik
You should mention get_browser() function, not just a link to it.
Notinlist
@ghostdog"In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.browscap.ini is not bundled with PHP"
soupagain
+1  A: 
<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

Prints:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)
Yada
+5  A: 
if (strpos($_SERVER['HTTP_USER_AGENT'], '(compatible; MSIE ')!==FALSE) {
    ...ie specific...
}

But! Don't!

There is rarely a good reason to be sniffing user-agent at the server side. It brings a bunch of problems, including:

  • browsers and other user-agents that lie about who they are, or strip the user-agent header completely, or generally make it hard to distinguish what the real browser is from the header text. For example the above rule will also detect Opera when it's spoofing IE, and IEMobile (Windows Mobile), which you may or may not want as it is a very different browser to desktop IE.

  • if you discriminate on the user-agent at the server-side, you must return a Vary: User-Agent header in the response, otherwise proxies may cache a version of the page and return it to other browsers that don't match. However, including this header has the side-effect of messing up caching in IE.

Depending on what it is you are trying to achieve, there is almost always a much better way of handling the differences between IE and other browsers at the client side, using CSS hacks, JScript or conditional comments. What is the real purpose for trying to detect IE in your case?

bobince