Browser detection in PHP

Written by lexa on November 12, 2008 – 22:32 -

browsersIt was short time ago. I was sitting in my room and thinking about browser-problems in this great and sick world. Then I went to the kitchen to make a tea, but made a coffee, because I was thinking about another things. Just like the programmers of the browsers, they wanted to make a best browser ever, but they failed.

So, now about our problem. We want make our application working in all browsers, because it’s good to make it work everywhere. So we have to aks the user agent (basically the client program, not the agent Smith from Matrix), what browser are you using? And we want make it so flexible, that we can ask him this every time. For this purpose we introduce a function:

function getBrowser()
{
  $ua = $_SERVER['HTTP_USER_AGENT']
  if (strstr($ua,'Opera')) {  // Opera
    $browser = ereg_replace(".+\(.+\) (Opera |v){0,1}([0-9,\.]+)[^0-9]*","Opera\\2",$ua);
    if(ereg('^Opera/.*',$ua)) {
      $browser = ereg_replace("Opera/([0-9,\.]+).*","Opera \\1",$ua);
    }
  } elseif (strstr($ua,'MSIE')) { // MSIE
    $browser=ereg_replace(".+\(.+MSIE ([0-9,\.]+).+", "Internet Explorer \\1",$ua);
  } elseif (strstr($ua,'Firefox')) { // Firefox
    $browser=ereg_replace(".+\(.+rv:.+\).+Firefox/(.*)", "Firefox \\1", $ua);
  } elseif (strstr($ua,'Mozilla')) {  //  Mozilla
    $browser=ereg_replace(".+\(.+rv:([0-9,\.]+).+","Mozilla \\1",$ua);
  } else {  // None of them.
    $browser=$ua;
  }
  return $browser;
}

If we want our PHP script to show us the browser, we write:

echo(getBrowser());

Now we can see, what kind of browser is used and use it in our aplication:

if (getBrowser() == 'Internet Explorer 6.0') {
echo ("Please install another Browser");
}

Thats it!


Tags: , , , , , ,
Posted in General, PHP, Web Design | No Comments »