14 Jan 2010 Ferado

How to detect if an iPhone user comes to your site

iPhone

Been thinking a lot about how I don’t have an iPhone lately. Then I thought…what if I wanted to keep iPhone users from visiting my site, in spite… Of course I’m not really going to do that. Only saying this because apparently you’re supposed to tell stories and have something exciting when you open for anything you write. Anyway..

Here’s how I figured out how to detect when an iPhone user is visiting your site, and how to send them to a specific page. That way, you can have a iPhone only site, or a mobile only site.

[ad key=”text-inline-small”]

Using Apache (.htaccess) mod_rewrite

[cc lang=”apache”]
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} iPhone
RewriteCond %{REQUEST_URI} !^/iphone-sucks.html # this is your iPhone or mobile only page
RewriteRule .* http://www.google.com/phone [R,L] # I’m being a jerk and sending them to Google :)
[/cc]

Now don’t blindly do the preceding snippet of code. Make sure you update it to match your site. And if you’ve never used mod_rewrite before, please do some more Googling. I’m just trying to show you how to check if a visitor is an iPhone user by using Apache (.htaccess).

Using PHP

[cc lang=”php”]

[/cc]

The preceding example shows you how to detect an iPhone user using PHP. Again, don’t blindly copy it without changing it a bit.

Using Basic JavaScript

[cc lang=”javascript”]
var agent = navigator.userAgent;
var isIphone = (agent.indexOf(‘iPhone’) != -1);
if (isIphone) {
window.location.href = ‘http://www.google.com/phone’;
}
[/cc]

That’s how you’re going to detect an iPhone user using basic JavaScript.

Using C# ASP.NET

[cc lang=”c#”]
// Request.ServerVariables[“HTTP_USER_AGENT”] or
// Request.UserAgent

if(Request.UserAgent.Contains(“iPhone”)) {
Response.Redirect(“http://www.google.com/phone”);
Response.End();
}
[/cc]

That’s how you detect if an iPhone user is coming to your site with C# ASP.NET. I’m not going to include a way to do it using VB.NET because if you know C#, you know VB.

iPhone User Agent

I know you’re curious about what the user agent for the iPhone looks like, so here it is:
Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16

The preceding user agent string is the user agent for the 3.0 iPhone. Here it is again if you want to copy and paste it into your code easier:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16

That’s it for now. Be good.