About Mobile Web Browsers

More and more people are using SmartPhones to access web pages. Although many of these phones do a very good job of rendering websites on a small screen, some very complex sites do not render properly. Also most handheld connections over phone networks are not as fast as cable, DSL or FIOS. You may loose a potential customer who is spending too much time waiting for your site.

What about Mobile Handheld Styles?

At first you may want to try to a pure CSS solution. For example, just create a style for handheld (media=handheld). But it will not work for many smartphones, particularly the iPhone, various BlackBerries (Storm, Curve, Pearl) and Android. That was enough to have me look for a different solution.

PHP To the Rescue

You can use PHP to detect what the User Agent is (or text held therein) and then redirect if it is a mobile browser. First, create a PHP page with the following script:

<?php

function DetectBrowser() {

$mobileBrowser= false; // set mobile browser as false till we can prove otherwise $user_agent = $_SERVER['HTTP_USER_AGENT'];
$newPage= "http://www.yourdomain.com/mobiledir/";
$toRedirect=false;

if (eregi('ipod',$user_agent)||eregi('iphone',$user_agent)) {
$toRedirect=true; }//end iphone check

if (eregi('blackberry',$user_agent)) {
$toRedirect=true; }//end blackberry check

if (eregi('opera mini',$user_agent)) { $toRedirect=true; }//end opera check

if (eregi('android',$user_agent)) { $toRedirect=true; }//end android check

if (preg_match('/(palm os|hiptop|avantgo|blazer|xiino|plucker|palm|elaine)/i', $user_agent)) {$toRedirect=true; }//end palm check

if (preg_match('/(windows ce; ppc;|windows ce; smartphone;|windows ce; iemobile)/i',$user_agent)) {
$toRedirect=true; }

if ($toRedirect) {
header('Location: '.$newPage); } //end check redirect

}//end detect browser function

?>

Save the file in an "inc" directory (or wherever you store your includes.

Reading the Script

Now that you have your script, just add the following code to each page that you wish to redirect. This should be the first command in your page, and put in place before the first <html> tag.

<?php include("inc/mobiledetect.php");
DetectBrowser();

?>

Next time, we will show you how to use cookies to allow users to override the browser detection script and access the full site using their handheld (smartphone) devices.