I was looking at ways to make web sites look the same in all browsers, and I came across a handy CSS hacks page at Web Devout. Some of this I already knew and had used, unfortunately including those that aren’t recommended. Since I am a big fan of valid CSS and Strict XHTML, I wanted a way that I could easily apply different CSS to specific browsers. After finding no simple JavaScript options, I searched for PHP options and came across a Drupal page that offered a “PHP Snippet” that I thought I could work with. As I posted on the site, I tested what the contents of the $_SERVER['HTTP_USER_AGENT'] variable were in the browsers that I would want to look the same, Safari, Firefox, Internet Explorer (6 and 7) and Opera.
I then did checks on the server variable and added a different stylesheet to the page for each browser. This could easily be adapted to redirect to different pages, include other php pages, etc. This is what I came up with:
<?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) { //Browser is Safari echo '<link href="Safari_only.css" rel="stylesheet" type="text/css" />'; } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox')) { //Browser is Firefox echo '<link href="FF_only.css" rel="stylesheet" type="text/css" />'; } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === true) { //Browser is Opera echo '<link href="Opera_only.css" rel="stylesheet" type="text/css" />'; } else { $msie_pos = strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'); if ($msie_pos === true) { //Browser is Internet Explorer $msie_version = substr($_SERVER['HTTP_USER_AGENT'], ($msie_pos + 5), 1); if ($msie_version < '7') { //Browser is Internet Explorer 6 (or below) echo '<link href="IE6_only.css" rel="stylesheet" type="text/css" />'; } else { //Browser is Internet Explorer 7 (or above) echo '<link href="IE7_only.css" rel="stylesheet" type="text/css" />'; } } else { //Other browser. } } ?>
I have since successfully used this in a personal site of mine and a site for work. If you have any questions/suggestions or even a better way of doing this, feel free to let me know.