Search Whitehat Blog

Monday 25 January 2016

Desktop to smartphone website redirection code

How to detect and redirect to a mobile site in PHP

With multiple versions of a site now common, it is important to redirect to the appropriate version depending on the type of device the user is using. For example if a user is viewing a website on a mobile device, we should be able to redirect to a mobile friendly version of our site. For this purpose we should be able to detect the device the user is using and act accordingly. This is where mobile detection libraries come in handy.



Case 1 : Redirecting a site to a mobile version

Say we have a normal website that we need to redirect to a mobile version if viewed from a mobile device. All the code required for mobile detection is in a single file ‘Mobile_Detect.php’, which we can include in our web pages or in the primary index file. To simplify discussion let us assume you have a website ‘example1.com’ with a single index file, and need to redirect to ‘mobile.example1.com’ if a mobile device is detected. We need to put the following in the header of the index file of ‘example1.com’.

/* Change path info depending on your file locations */
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
 
if($detect->isMobile()) {
    header('Location: http://mobile.example1.com/');
    exit;
}

The above code will now redirect the main site to a mobile version if viewed from a mobile. Some other use cases to redirect are given below.

// Any tablet device.
if( $detect->isTablet()) {
 
}
 
// Exclude tablets.
if( $detect->isMobile() && !$detect->isTablet()) {
 
}
 
// Check for a specific platform with the help of the magic methods:
if( $detect->isiOS()) {
 
}
 
if( $detect->isAndroidOS()) {
 
}
 
if( $detect->isWindowsPhoneOS()) {
 
}

Case 2: Loading different resources depending on the device

We can load or modify existing content based on the users device profile. For example we could load a different CSS for a mobile or a tablet.

$detect = new Mobile_Detect;
 
if($detect->isMobile() || $detect->isTablet()) {
    echo "<link rel='stylesheet' href='mobile.css type='text/css' />";
} else {
    echo "<link rel='stylesheet' href='style.css type='text/css' />";
}

Note that mobile detection is a moving platform, and as new devices are introduced you will need to update the library with new versions. Also, as the library relies on HTTP headers to sniff the device signature, it could sometimes give incorrect results if the headers are tampered with.