03-10-2009, 07:50 AM
I'm making a new website and had a problem with CSS positioning in Opera. Well, maybe not Opera (it worked as it should), but Firefox and IE - they made some dstrange things to my CSS. I tried to make it work on all browsers, but in time I had enough. So, I needed a simple browser detection script to load different stylesheets for Opera and other browsers. After googling a bit, I've found a script that looked promising and tweaked it a bit.
Here's the result (put it in <head> section of the page):
Here's the result (put it in <head> section of the page):
Code:
<?
$browsers = "mozilla msie gecko firefox ";
$browsers.= "konqueror safari netscape navigator ";
$browsers.= "opera mosaic lynx amaya omniweb";
$browsers = split(" ", $browsers);
$nua = strToLower( $_SERVER['HTTP_USER_AGENT']);
$l = strlen($nua);
for ($i=0; $i<count($browsers); $i++){
$browser = $browsers[$i];
$n = stristr($nua, $browser);
if(strlen($n)>0){
$GLOBALS["ver"] = "";
$GLOBALS["nav"] = $browser;
$j=strpos($nua, $GLOBALS["nav"])+$n+strlen($GLOBALS["nav"])+1;
for (; $j<=$l; $j++){
$s = substr ($nua, $j, 1);
if(is_numeric($GLOBALS["ver"].$s) )
$GLOBALS["ver"] .= $s;
else
break;
}
}
}
$browser = $GLOBALS["nav"];
if ($browser == "opera") {
print "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"style_opera.css\" />";
}
else {
print "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"style_other_browsers.css\" />";
}
?>
Now, when the page is opened in Opera, it loads style_opera.css, and if it's different browser, it loads style_other_browsers.css.
You can make different stylesheets for all major browsers (the list is in the script).
This script works not only as a stylesheet loader, it can be used in any way you can think of (different greetings on your site for IE and Firefox users, for example). And it not only shows the browser family, but also can show it's version (using $GLOBALS["ver"])