I wasn't sure if 4images had an easy way to do this already, and I needed it, so I set this up on my site.
includes/functions.php
Find
Replace
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| function browser_info($agent=null) { // Declare known browsers to look for $known = array('msie', 'firefox', 'chrome', 'safari', 'webkit', 'opera', 'netscape', 'konqueror', 'gecko');
// Clean up agent and build regex that matches phrases for known browsers // (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor // version numbers. E.g. "2.0.0.6" is parsed as simply "2.0" $agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']); $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';
// Find all phrases (or return empty array if none found) if (!preg_match_all($pattern, $agent, $matches)) return array();
// Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase, // Opera 7,8 have a MSIE phrase), use the last one found (the right-most one // in the UA). That's usually the most correct. $i = count($matches['browser'])-1; return array($matches['browser'][$i] => $matches['version'][$i]); }
?> |
includes/page_header.php
Find
Replace
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| $ua = browser_info();
if ($ua['firefox']) { $doctype = ""; } else { $doctype = "<!DOCTYPE HTML>"; }
if ($ua['msie']) { $msie = 1; } else { $msie = 0; }
$site_template->register_vars(array( "doctype" => $doctype, "msie" => $msie ) );
?> |
Now use the example to create your own. The examples allow you to display a different DOCTYPE for Firefox using {doctype},
or you can show some html to Internet Explorer users only, by using {if msie} ...my html... {endif msie}
Other check types:
Replace firefox with a browser that we setup in the $known = array
1 2 3 4 5
| if ($ua['firefox']) ... // true if ($ua['firefox'] > 3) ... // true if ($ua['firefox'] > 4) ... // false if ($ua['browser'] == 'firefox') ... // true if ($ua['version'] > 3.5) ... // true |
Very simple, I know. But very useful. It saved my site from being broken in some browsers by letting me change the doctype, and displaying a message to IE users to get a better browser.