87

I want to do a conditional in PHP for the different versions of Internet Explorer along the lines of:

if($browser == ie6){ //do this} elseif($browser == ie7) { //dothis } elseif...

I have seen many variations on similar code, but looking for something super simple that is very easy to code to do some simple if and else and do different things.

Thanks

EDIT: I need this to show some different messages to users so CSS conditionals etc are no good.

Cameron
  • 27,963
  • 100
  • 281
  • 483
  • 4
    Are you looking to serve differing CSS? In that case, consider [conditional comments](http://www.quirksmode.org/css/condcom.html). Less hassle – Pekka Mar 14 '11 at 17:49
  • 1
    Apparently IE10 doesn't support conditional statements. – CharlieM Apr 22 '13 at 15:47

17 Answers17

130

This is what I ended up using a variation of, which checks for IE8 and below:

if (preg_match('/MSIE\s(?P<v>\d+)/i', @$_SERVER['HTTP_USER_AGENT'], $B) && $B['v'] <= 8) {
    // Browsers IE 8 and below
} else {
    // All other browsers
}
Temüjin
  • 15,371
  • 8
  • 35
  • 57
Cameron
  • 27,963
  • 100
  • 281
  • 483
  • 75
    This pattern will recognize Internet Explorer 10 as Internet Explorer 1. – chaos Jul 20 '12 at 23:49
  • 2
    I think some versions of Opera will match this, but they can be filtered out by checking for 'Opera'. – Liam Sep 06 '12 at 11:32
  • So would you use 4 different preg_matches to get the four versions? Seems inefficient... plus doesn't even support 9 as requested... – Jake May 09 '13 at 20:45
  • 45
    just change it to `'/(?i)msie [2-8]/'`. Do you really need to check for [ie 1](http://en.wikipedia.org/wiki/Internet_Explorer_1)? It was released in 1995 and was replaced by ie2 a few months later. – Landon May 10 '13 at 16:07
  • 8
    I changed it to [4-8]. IE updates are getting more and more frequent and I really want to make sure I don't have to make a similar change during the lifetime of the web app I'm working on (as it only has a lifespan of 3 years). If someone is browsing the web with IE 5 or less, they have WAY more problems than viewing my web app. – Adam Erstelle Nov 22 '13 at 01:35
  • 2
    If you just add a period it will check for the lower number versions without checking for version 10, 20, etc. `'/(?i)msie [1-8]\./'` – michaellindahl Feb 11 '14 at 20:04
  • I definitely agree, @AdamErstelle. Besides, pretty much the only IE browsers that are less than IE 9 are 7 and 8. However, with a fresh install of Windows XP comes IE 5. – andrew Jan 27 '15 at 23:56
  • For me useragent is Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko – Kiren S Apr 26 '16 at 11:03
86

A version that will continue to work with both IE10 and IE11:

preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);
if(count($matches)<2){
  preg_match('/Trident\/\d{1,2}.\d{1,2}; rv:([0-9]*)/', $_SERVER['HTTP_USER_AGENT'], $matches);
}

if (count($matches)>1){
  //Then we're using IE
  $version = $matches[1];

  switch(true){
    case ($version<=8):
      //IE 8 or under!
      break;

    case ($version==9 || $version==10):
      //IE9 & IE10!
      break;

    case ($version==11):
      //Version 11!
      break;

    default:
      //You get the idea
  }
}
Doug
  • 3,312
  • 1
  • 24
  • 31
  • 2
    I am not sure why you used a switch statement when it seems like an if/then would be more appropriate, but this worked great. And apparently you were the only one who read that the OP wanted separate version support. – Jake May 09 '13 at 20:42
  • we actually had to target IE including 11 and this worked beautifully – code_monk May 28 '14 at 15:21
  • Newer devices can have different attributes in the IE11 user agent, as mentioned here: github.com/woothee/woothee-java/issues/6. To fix that, the regular expression should be changed to this: `Trident\/\d{1,2}.\d{1,2};(.*)rv:([0-9]*)`, and `$version = $matches[1];` should be changed to `$version = ($matches[2] == 11)?$matches[2]:$matches[1];`. You can see an example of the regex here: regexr.com/3fb4k. – jdgregson Feb 21 '17 at 09:05
16

You can check the HTTP_USER_AGENT server variable. The user agent transfered by IE contains MSIE

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) { ... }

For specific versions you can extend your condition

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.') !== false) { ... }

Also see this related question.

Community
  • 1
  • 1
Daff
  • 43,734
  • 9
  • 106
  • 120
  • @dixus for IE11 you have to do this `preg_match('/Trident\/7.0; rv:11.0/', $_SERVER['HTTP_USER_AGENT'])` – Andres SK Dec 09 '14 at 22:05
16

Here is a great resource for detecting browsers in php: http://php.net/manual/en/function.get-browser.php

Here is one of the examples that seems the simplest:

<?php
function get_user_browser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $ub = '';
    if(preg_match('/MSIE/i',$u_agent))
    {
        $ub = "ie";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $ub = "firefox";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $ub = "safari";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $ub = "chrome";
    }
    elseif(preg_match('/Flock/i',$u_agent))
    {
        $ub = "flock";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $ub = "opera";
    }

    return $ub;
}
?>

Then later in your code you could say something like

$browser = get_user_browser();
if($browser == "ie"){
    //do stuff
}
Michael Jasper
  • 7,962
  • 4
  • 40
  • 60
  • 1
    Is there any reason to set $ub, and then return it at the end. Surely it's more efficient (skips out some unnecessary if's) to return the name of the browser instead of setting the variable. – w4etwetewtwet Mar 13 '13 at 20:28
  • 1
    Some simple, stock browser testing, but it doesn't do versions like the request... – Jake May 09 '13 at 20:42
  • chrome useragent contains safari. so above test should report chrome as safari. the order should be reversed. check keyword chrome first. – Average Joe Oct 24 '18 at 09:06
11

I do this

$u = $_SERVER['HTTP_USER_AGENT'];

$isIE7  = (bool)preg_match('/msie 7./i', $u );
$isIE8  = (bool)preg_match('/msie 8./i', $u );
$isIE9  = (bool)preg_match('/msie 9./i', $u );
$isIE10 = (bool)preg_match('/msie 10./i', $u );

if ($isIE9) {
    //do ie9 stuff
}
Vince Lowe
  • 3,521
  • 7
  • 36
  • 63
5
if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/(?i)msie|trident|edge/",$_SERVER['HTTP_USER_AGENT'])) {
// eh, IE found
}
xsor
  • 1,074
  • 11
  • 11
5

PHP has a function called get_browser() that will return an object (or array if you so choose) with details about the users' browser and what it can do.

A simple look through gave me this code:

$browser = get_browser( null, true );
if( $browser['name'] == "Firefox" )
    if( $browser['majorversion'] == 4 )
        echo "You're using Firefox version 4!";

This is not a surefire way (as it reads from HTTP_USER_AGENT, which can be spoofed, and will sometimes be analyzed wrong by php), but it's the easiest one that you can find as far as I know.

Mike S
  • 399
  • 3
  • 15
  • 2
    requires server side configurations to work. I am not sure how reliable it is for products to run on different servers – latvian Jan 23 '14 at 01:13
4

Here's a little php function I wrote that uses the regex directly from MSFT's suggested javascript sniffing code from this article: http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx

/**
* Returns the version of Internet Explorer or false
*/
function isIE(){

    $isIE = preg_match("/MSIE ([0-9]{1,}[\.0-9]{0,})/",$_SERVER['HTTP_USER_AGENT'],$version);
    if($isIE){
        return $version[1];
    }
    return $isIE;

}
minorgod
  • 652
  • 6
  • 7
4

You can as well look into PHP's get_browser(); http://php.net/manual/en/function.get-browser.php

Maybe you'll find it useful for more features.

tomsseisums
  • 13,168
  • 19
  • 83
  • 145
  • 3
    Neat. But it requires a setting in your php.ini which could be a problem for some users. – Jake May 09 '13 at 19:56
3

Checking for MSIE only is not enough to detect IE. You need also "Trident" which is only used in IE11. So here is my solution which worked an versions 8 to 11.

$agent=strtoupper($_SERVER['HTTP_USER_AGENT']);
$isIE=(strpos($agent,'MSIE')!==false || strpos($agent,'TRIDENT')!==false);
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
2

You could use something like this for different messages or div/css

<!--[if IE 6]>
<style type="text/css">
div.ie6 { display:block; }
</style>
<![endif]-->

<!--[if IE 7]>
<style type="text/css">
div.ie7 { display:block; }
</style>
<![endif]-->

<!--[if IE 8]>
<style type="text/css">
div.ie8 { display:block; }
</style>
<![endif]-->

<!--[if IE 9]>
message1
<![endif]-->

<!--[if !IE 6]>
message2
<![endif]-->

<!--[if lt IE 8]>
message3
<![endif]-->

OR use different div of css

<!--[if lte IE 8]>
<style type="text/css">
div.lteie8 { display:block; }
</style>
<![endif]-->

<!--[if gt IE 6]>
<style type="text/css">
div.gtie6 { display:block; }
</style>
<![endif]-->

<!--[if gte IE 6]>
<style type="text/css">
div.gteie6 { display:block; }
</style>
<![endif]-->
Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
Enrico Tempesti
  • 125
  • 1
  • 5
2

You can do this via parsing the user-agent header:

http://php.about.com/od/learnphp/p/http_user_agent.htm

Be wary that this is not very reliable and can be trivially spoofed.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
2

'HTTP_USER_AGENT' Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.

So I assume you'll be able to get the browser name/id from the $_SERVER["HTTP_USER_AGENT"] variable.

arnehehe
  • 1,386
  • 1
  • 17
  • 33
1

but still useful - and works with IE11 ! here is another short way to get the common browsers returned for css class:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

So this function returns: 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

hope it helps

antoni
  • 5,001
  • 1
  • 35
  • 44
0

Notice the case in 'Trident':

if (isset($_SERVER['HTTP_USER_AGENT']) &&
    ((strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false) || strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== false)) {   
     // IE is here :-(
    }
Vlado
  • 3,517
  • 2
  • 26
  • 24
0

if you have Internet Explorer 11 and it's running over a touch screen pc, you must use: preg_match('/Trident/7.0; Touch; rv:11.0/', $_SERVER['HTTP_USER_AGENT']) instead of: preg_match('/Trident/7.0; rv:11.0/', $_SERVER['HTTP_USER_AGENT'])

-1

A tridend based approach would be better. Here is a quick function for checking IE 8.

<?php
function is_IE8(){
   if(strpos(str_replace(' ', '', $_SERVER['HTTP_USER_AGENT']),'Trident/4.0')!== FALSE){
       return TRUE;
   };
   return FALSE; 
} 
?>
sajin tm
  • 323
  • 3
  • 9