Detecting Mobile Devices with PHP
I have been using a great function written by Andy Moore on one of my personal sites that I run for my friends to detect Mobile Phones with php which worked a treat until a friend of mine bought himself a nice shiny iTouch and found the site still redirected him to the sites dedicated mobile pages. After the jealously of finding out my friend had a nice iTouch subsided I set to work to implement the detect iPhone function.
I used the following in my header file to detect mobile and iPod devices:
// detect and redirect mobile browsers
if(detect_mobile_device()){
header('Location: /mobile/'); // Direct Mobiles to Mobile Site
exit;
}
//send iphone to specific site
if(detect_iphone()){
header('Location: /'); //Direct iPhone to normal Site
exit;
}
What I got was a continuous loop as both the detect_mobile_device() function and the detect_iphone() function were both returning true – Ouch!
I used this work around to great effect: -
// Send ihone to specific home
if(eregi('iPhone',$_SERVER['HTTP_USER_AGENT'])
or eregi('iPod',$_SERVER['HTTP_USER_AGENT']))
{
$set = 1;
}
if ($set !=1)
{
if(detect_mobile_device())
{
header('Location: /mobile/');
exit();
}
}
This worked a treat with iTouch and iPhones being left to go to my homepage whilst mobile browsers being pushed to the mobile page. This works because $set is only equal to 1 if an iPhone or iTouch is detected in which case the detect_mobile_device() is not run. If the device is not a iPhone or an iTouch then detect_mobile_device() is called to test for a mobile browser.






Latest from Twitter
There’s a much slicker function to detect now!
Thanks for the mention!