Browser detection in PHP
With Joomla! templates, there are various ways to deal with different browser-types. This might be necessary to add specific CSS-code for specific browsers, so within the world of webdesign there are already many tricks: A good designer knows about the VisualBasic-tricks for IE, but few know that there is also a Joomla!-class providing excellent browser-detection.
IE Conditional Comments
The most famous solution to deal with IE-specific tricks is to use a separate CSS-stylesheet that is loaded only by the IE-browser family. To do this, you use conditional comments which only work under IE because of its VB-script functionality.
<!--[if IE 6]> <link rel="stylesheet" type="text/css" src="templates/<?php echo $this->template;?>/css/ie6.css" /> <![endif]-->
There are different variations here: You can check for browsers equaling a specific browser-version (like IE6 above), or match a browser lower or higher than a specific version.
The Joomla! way: Browser detection
The VisualBasic-trick only works for IE-browsers. For other browsers, you either need weird tricks that might involve JavaScript. Fortunately, the Joomla! Framework contains a class for browser detection, which allows you to dynamically build the template-output depending on the browser-version. This works, because when a browser requests a certain webpage, it sends a HTTP Request which also contains the so-called User Agent. Based on this User Agent you can make certain decisions.
jimport('joomla.environment.browser'); $browser = JBrowser::getInstance(); $ie6 = ($browser->getBrowser() == 'msie' && $browser->getVersion() == '6.0') ? true : false; if($ie6 == true) { ... }
Using our Yth class
With our Yireo Template Helper we provide you with a simple Yth-class, which makes adding these tricks to your template a lot easier. For instance, if you want to include a stylesheet "ie6.css" if the IE6 browser is used, you can add the following:
<?php if(Yth::isBrowser('ie6')) { ?> <link rel="stylesheet" type="text/css" src="templates/<?php echo $this->template;?>/css/ie6.css" /> <?php } ?>
Conclusion
The main benefit of using the PHP-method, instead of the IE conditional statements, is that you can also check for other browsers like Opera, Chrome and Safari.
Created on Friday, 12 March 2010Modified on Saturday, 27 February 2010
More tutorials in this section
- Force IE8 to use IE7 Compatibility Mode
- Browser detection in PHP
- Custom Joomla! template layouts with PHP-code
- Building a splitmenu with Yireo Template Helper
- Crunching Joomla! CSS with the Yireo Template Helper
- Disabling CSS in Joomla! extensions
- Modules on the Joomla! offline page
- Writing your own Joomla! splitmenu
- Joomla! output override of mod_mainmenu
