Browser Collections

Search

Kamis, 01 April 2010

Browser detection in PHP

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:

01function getBrowser()
02{
03 $ua = $_SERVER['HTTP_USER_AGENT']
04 if (strstr($ua,'Opera')) { // Opera
05 $browser = ereg_replace(".+\(.+\) (Opera |v){0,1}([0-9,\.]+)[^0-9]*","Opera\\2",$ua);
06 if(ereg('^Opera/.*',$ua)) {
07 $browser = ereg_replace("Opera/([0-9,\.]+).*","Opera \\1",$ua);
08 }
09 } elseif (strstr($ua,'MSIE')) { // MSIE
10 $browser=ereg_replace(".+\(.+MSIE ([0-9,\.]+).+", "Internet Explorer \\1",$ua);
11 } elseif (strstr($ua,'Firefox')) { // Firefox
12 $browser=ereg_replace(".+\(.+rv:.+\).+Firefox/(.*)","Firefox \\1", $ua);
13 } elseif (strstr($ua,'Mozilla')) { // Mozilla
14 $browser=ereg_replace(".+\(.+rv:([0-9,\.]+).+","Mozilla \\1",$ua);
15 } else { // None of them.
16 $browser=$ua;
17 }
18 return $browser;
19}

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

1echo(getBrowser());

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

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

Thats it!

0 komentar:

Posting Komentar