Wednesday, December 26, 2007

Mobile Phone Site Detection

I got a Palm Centro mobile device for Christmas and it got me to thinking about the number of potential employers/clients that might use their mobile phones to view my resume or company site online. I've been quite happy with Google's mobile-versioned sites, like www.google.com/calendar/m and decided that I'd better follow the leader.

It wasn't as easy as you might think to find a good mobile-phone detection script online, at least not one that worked for the Centro. After four failed attempts, I found this one on brainhandles.com.




function checkmobile()
{
if(isset($_SERVER["HTTP_X_WAP_PROFILE"]))
return true;

if(preg_match("/iphone/i",$_SERVER["HTTP_USER_AGENT"]))
return false;

if(preg_match("/wap\.|\.wap/i",$_SERVER["HTTP_ACCEPT"]))
return true;

if(isset($_SERVER["HTTP_USER_AGENT"]))
{

$uamatches = array("midp", "j2me", "avant", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows\ ce", "mmp\/", "blackberry", "mib\/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up\.b", "audio", "SIE\-", "SEC\-", "samsung", "HTC", "mot\-", "mitsu", "sagem", "sony", "alcatel", "lg", "eric", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "\d\d\di", "moto");

foreach($uamatches as $uastring)
{
if(preg_match("/".$uastring."/i",$_SERVER["HTTP_USER_AGENT"]))
return true;
}
}
return false;
}
#example
if(checkmobile())
{
header('Location: http://www.yoursite.com/m/index.html');
exit;
}

if(!checkmobile())
{
header('Location: http://www.yoursite.com/');
exit;
}
?>



It's a PHP script, of course. For my purposes, I just created an index.php file and set "DirectoryIndex index.php index.html". The first thing the visitor hits is the php file, which either redirects to the main index.html file or the mobile version in the "m" directory.

No comments: