Wednesday, February 16, 2011

Redirect Mobile Devices with PHP


Are you looking for mobile website redirection script. Take a look at this post I want to explain how to detect mobile user agents like Android, Iphone and Blackberry. Many people are suggested to redirect with .htaccess file but I had implemented this with PHP. It is very easy just few lines of code.

Redirect mobile devices


Demo: Try to open labs.9lessons.info with mobile devices it will be redirect totouch.9lessons.info (mobile site)

$_SERVER - Server and execution environment information (More info)
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>

My Android browser Output:

Mozilla/5.0 (Linux; U; Android 2.1-update1; en-in; HTC_Wildfire_A3333 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari

user_agent.php
Usining strpos() function find position of first occurrence of a string. (more details)
<?php
$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone || $android || $palmpre || $ipod || $berry == true)
{
header('Location: http://mobile.site.com/');
//OR
echo "<script>window.location='http://mobile.site.com'</script>";
}
?>

Index.php or Home.php
You have to include like following script.
<?php
include('user_agent.php'); // Redirecting http://mobile.site.info
// site.com data
?>

No comments:

Post a Comment