How to Write Browser Specific Code with PHP
So you want to write code that only appears on certain browsers… There are a number of reasons to want to do this. The first time I personally needed to do this occurred when I was trying to embed an mp3 on a certain page. For some reason I could not write the code so that the mp3 would play on the browsers I test on (IE, Firefox, and Opera), and validate at the same time. If I remember correctly, it was Internet Explorer that was causing the problem. The solution I came up with was to use a little PHP to find out when the user was using IE, and then embed the mp3 in non-valid code if that was the case.
This solution led to the mp3 always playing correctly and the page always validating, because the W3C validator never identifies itself as IE. This might not be the most ethical way to reach W3C compliance, but it works.
Another time I remember needing to write browser specific code is when I was having a problem with IE 6 not displaying my .png images correctly. I googled around and found a couple of solutions to the problem, but both of them ended up messing up the overall layer locations on my pages. Instead of troubleshooting that problem, I went with the quick solution and decided to display .gifs when the user had IE 6. If the user had another browser that had .png problems I figured that was too bad for him.
How to do it:
First you need to write a little line of code to figure out what browser your user has. Here is how to do that with PHP:
- $visitorsOS = $_SERVER['HTTP_USER_AGENT'];
Here are three examples of what $visitorsOS can look like
- Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET
- Opera/9.51 (Windows NT 5.1; U; pl)
- Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008052906 Firefox
The first user has Internet Explorer 6, the second Opera 9.51, and the third Firefox.
Now that we know more information than we really need about the visitor’s computer we need to put that information to good use. Say you want to write code that will only appear if the user is running any version of Internet Explorer. In that case you would do this:
if (eregi(’MSIE’,$visitorsOS)){
CODE THAT WILL ONLY APPEAR IF USER HAS IE
}
else{
CODE THAT WILL APPEAR IN ALL OTHER CASES
}
I use eregi, a case insensitive regular expression match instead of ereg, a case sensitive regular expression match. I don’t remember if I do this out of paranoia, or if I actually found a case where Internet Explorer identified itself as msie. In either case eregi won’t hurt anything so it is what I use. Wanting to write the code for specific versions of IE would only require a small change. instead of …(eregi(’MSIE’…) I would use something like (eregi(’MSIE 6.0′…) if I wanted code that only appeared for MSIE 6.0.








































