Paulund
2012-05-18 #javascript

Detect IPhone, IPad or IPod

With mobile devices becoming more and more popular there will be times when you need to do something different for users coming to your site from one of these mobile devices. If you want to change the design depending on the mobile device you will use media queries. But if you want to change functionality such as Javascript then you can use the below snippet to do something different for mobile devices.

Javascript


<script>
if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
	alert('You are using an iPhone, ipod or an ipad');
}
</script>

I've added this script to this page so if you visit this page on a iPhone, ipod or an ipad then you will see an alert box.


<script>
if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
	alert('You are using an iPhone, ipod or an ipad');
}
</script>

PHP

If you are using PHP and want to know if the current user is using an iPhone, iPad or iPod then you can get the device they are using by looking at the HTTP_USER_AGENT variable.


function isIphone()
{
    return (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPhone');
}

function isIpad()
{
    return (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');
}

function isIpod()
{
    return (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPod');
}

Htaccess

If you want to redirect user's to different websites depending on what device they are using you can use htaccess to redirect user, again with htaccess we can access the HTTP_USER_AGENT.


RewriteCond %{HTTP_USER_AGENT} ^.*iPhone.*$
RewriteRule ^(.*)$ http://iphone.yourdomain.com [R=301]

RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ http://ipad.yourdomain.com [R=301]

RewriteCond %{HTTP_USER_AGENT} ^.*iPod.*$
RewriteRule ^(.*)$ http://ipod.yourdomain.com [R=301]