How to Detect Visitor Browser Type

Jul 04, 2013, by admin

Modernizr is useful for feature detection of the browsers, so that we are able to patch the functionalities that are not supported. We can also use CSS3 media query, though it is not designed to retrieve browser information, it is useful to address the website presentation particularly in mobile browsers.

PHP Browser Detection

However, all of those methods are only altering the front side, while the actual content in the document’s markup remain unaffected. Say, we have two <div> elements one for Internet Explorer, and one for the other. These two elements will actually remain on the document regardless of the browsers.

In some cases, these methods might not be the ideal solution. So, the only viable option would be to use the server-side language, like PHP. If you are using WordPress, there is an easy to do so with a plugin called PHP Browser Detection.
Conditional Functions

When this plugin has been activated, it will give you nothing in the Dashboard. Instead, it provides several conditional functions to use in your theme files – such as page.php, index.php and others. It allows detection in all popular desktop and mobile devices – such as iPad and iPhone.
Basic Usage

Let’s see some usage examples. Say, we want to show notification only to Internet Explorer users. We can write something like this inside the header.php under the <body>.
view plaincopy to clipboardprint?

<?php if ( is_IE() ) {
$browserInfo = php_browser_info();
$browser = $browserInfo[browser];
$version = $browserInfo[version];

echo ‘<div>You are using ‘.$browser.’ ‘.$version.’ . Please, update your browser for better experience.</div>’;
}; ?>

With a few style adjustment in the stylesheet, Internet Explorer users will see the following.

But, when we see it in other browsers – Firefox, Opera, Safari and Chrome– the notification markup is not generated.

As mentioned, we can also target for mobile devices, which is very useful to optimize your WordPress site on the mobile platform. Assuming that you have enabled the post thumbnail support in your theme, we can add the following function to your index.php to serve lower image resolutions in mobile device, and higher resolutions for desktop browsers.
view plaincopy to clipboardprint?

<?php if ( is_mobile() ) {
the_post_thumbnail( ‘small’ );
} else {
the_post_thumbnail( ‘large’ );
}; ?>

 

Hope so this post will be useful see you all in the next post