Industry guru Dave Taylor offers free tech support on a wide variety of technical and business topics, including HTML, Apple iPhone, online advertising, Cascading Style Sheets, Web design, management, Unix, Linux, search engine optimization, online dating, Mac OS X, shell script programming and Microsoft Windows.

How do I detect an iPhone user coming to my site?

Amazon.com's jumped on the wagon, and Meebo has too: they automatically give you a different version of their site if you're browsing from an Apple iPhone. I want to do that too. How the heck do I detect that a visitor has an iPhone?


Dave's Answer:

The key to detecting a browser type is to remember that there's an environment full of information transmitted with each query sent from the web browser to the server. It includes the obvious things like the requested data file (which can be an HTML document, GIF or JPEG image, AVI movie, FLV animation or related) and the IP address of the browser's computer, but it also includes a critical variable called HTTP_USER_AGENT.

Visit with a regular browser from a regular computer and you'll see something like this:

HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)

Here you can see that I'm testing from Firefox (which identifies itself as Mozilla for historical reasons) running on Windows XP (though it's identifying it as Windows NT for some cockamainie reason) and that I'm also running .NET.

Grab that same environment value from a slick Apple iPhone query, though, and the values are quite a bit different:

HTTP_USER_AGENT=Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en)
AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C25 Safari/419.3

Pretty interesting reading if you're a geek: You can see where it's also identifying itself as Mozilla, but this time as Mozilla/5.0 rather than Mozilla/4.0. The string "iPhone" appears, which is what we'll key on, but notice also that it says that it's on a system with a "CPU like Mac OS X", just as we iPhone users have been suspecting for a while.

You can see the basic test we'll need to do here to ascertain if the visitor is using an iPhone or not: if their HTTP_USER_AGENT environment value contains the string "iPhone", we've got a match. Otherwise it's something else on some other device or computer.

You can do this test and act on it in a zillion different places, ranging from the actual Web server ruleset to JavaScript code to PHP conditional code to even having a separate "gateway" script page that everyone hits and redirects them to the iPhone or non-iPhone version of your Web page and site.

A JavaScript snippet might look like this:

var agent=navigator.userAgent.toLowerCase();
var is_iphone = ((agent.indexOf('iphone')!=-1);
if (is_iphone) { conditional code goes here }

Rather do it as a shell script? Me too. Here's how I'd do that as a rudimentary Linux shell script:

#!/bin/sh

if [ ! -z "$(echo $HTTP_USER_AGENT | grep iPhone)" ] ; then
  echo "Location: iphone/index.html"
else
  echo "Location: index2.html"
fi
exit 0

You can also have the conditional directly in CSS itself, if you're really into cryptic notations:

<!--#if expr="(${HTTP_USER_AGENT} = /iPhone/)"-->
<style type="text/css">
<!--
here's where you'd include special styles for the iPhone
-->
</style>
<!--#else -->
<style type="text/css">
<!--
regular web browser style and CSS information goes here
-->
</style>
<!--#endif -->

The basic idea in either case is that once you have detected that they're running an iPhone, you can modify what you deliver to them, either changing what's on the page, perhaps giving them a completely different version of the page, or even taking them to a different site entirely.

Hope that helps you out! Don't forget while you're here that I have quite a lot of iPhone help here too.



Help others find this article at Del.icio.us, Digg, Netscape, Reddit, and Stumble Upon    

Subscribe!

Never miss another useful Q&A article again! Subscribe to AskDaveTaylor with Google Reader.

Comments

var agent=navigator.userAgent.toLowerCase();
var is_iphone = ((agent.indexOf('iPhone')!=-1);
if (is_iphone) { conditional code goes here }

I think you might want to do indexOf('iphone') since agent is all lower case.

Posted by: Dude at October 12, 2007 5:59 PM

Windows XP is the same as Windows NT 5.1!

It's the same thing as you said about Firefox being called Mozilla 5.0

http://en.wikipedia.org/wiki/Windows_NT#Releases

Posted by: James at October 24, 2007 2:21 PM

Dave,

Thank you for this info.

I have been trying to use the Javascript you listed here to redirect iphone users to a different version of a site, with no luck.

How would you do it if you had to use javascript?

Posted by: Chris Wilson at November 14, 2007 2:08 PM

Ruby on rails has auto detection for various types of request:


respond_to do |format|
format.html #index.html.erb
format.xml { render :xml => @articles.to_xml }
format.rss { render :layout => false } #index.rss.builder
format.iphone do #action.iphone.erb
render :layout => false
end
end

Posted by: Frederico Araujo at December 25, 2007 1:17 PM

Hi
I am developing site for small browsers.Currrently i am facing issue for Iphone and Blackjack.On this i am gettting large browsers screens .I am detecting iphone browser through user-agent but since i dont have iphone i thought of checking it on simulator which gives me information of IE.

also i would like to know how to detect visitior coming from blackjack.

Posted by: first time user at January 31, 2008 11:47 PM

Hey Guys,

The javascript in his post is a bit broken, here is the fixed code:

var agent=navigator.userAgent.toLowerCase();
var is_iphone = (agent.indexOf('iphone')!=-1);
if (is_iphone) { /* execution here */ }

Posted by: Amadeus at February 13, 2008 11:38 PM

Hello,

I am trying to implement your javascript into my site for a page redirection when the user visits the site with a Iphone but i am experiencing problems i was hoping that you could help me by telling me what i did wrong for the javascript coding.


var agent=navigator.userAgent.toLowerCase();
var is_iphone = (agent.indexOf('iphone')!=-1);
if (is_iphone) { scr="http://www.qualitycontactsolutions.com/iphone/" }


Posted by: Michael Garfinkel at February 19, 2008 4:50 PM

Michael -

I think you need to use window.location for your redirect:

var agent=navigator.userAgent.toLowerCase();
var is_iphone = (agent.indexOf('iphone')!=-1);
if (is_iphone) { window.location ="http://www.qualitycontactsolutions.com/iphone/" }

Posted by: Phil at February 21, 2008 10:38 AM

<script language=javascript>
<!--
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
{
location.replace("iphone-version.html");
}
-->
</script>

Posted by: Miki at February 25, 2008 5:43 PM

Miki, that worked. Thanks.

Posted by: Steven Eckelberry at April 15, 2008 9:19 PM

I have created a website using iWeb. I would like to insert some html code (or some type of code) that recognizes when a viewer is visiting on an iPhone versus a regular computer. I've read the above and tried inserting the java script in the html snippet but it does not work. Do you know if there is a way to do this?

Thanks,
Tom Fawbush

Posted by: Tom Fawbush at May 21, 2008 4:25 PM

you can also use a more advanced web service such as handsetdetection.com which returns real time information on which devices are accessing your site - and then allowing you to adjust the view. Data it returns includes screensize, browser, phone make and model and also location based information.

Posted by: david at July 16, 2008 8:04 PM

Dear Dave

I've made a Drupal web site, and I wish use Jquery to reveal iPhone. Is there a way to reveal iPhone by jquery?

I've reveal the safari browser woth this code:

if ($.browser.safari) {
alert("se hai l'iPhone Aggiungi alla Home questo sito");
}

BUt I can't understand if the safari browser is for iPhone or Mac...

Someone can help me please?


Posted by: walter at September 25, 2008 2:28 PM


Heya, is there any information about to see other phones such as Nokia ? i.e so i can make a custom website for nokia phones too ??

feel free to email me.

thankyou in advance.

Posted by: nomadarts at November 2, 2008 7:26 PM

Excellent info. I'll be trying this on my site for sure!

Posted by: Winsock at July 4, 2009 4:53 AM

holy cow, that's a work of genius, after hours spent trying to kludge position:fixed to work I can just go round it and present an iphone optimized version for my client as well as the scrolling desktop version.

absolutely brilliant. thankyou.

Posted by: spike at September 14, 2009 7:18 PM

How do I make a conditional statement that hides the contents of the tag from iPhone and iPod Touch users?

If iPhone or iPod Touch, hide xyz. xyz is not a div, but rather a few script tags, so I don't believe it would not work with css.

Thanks in advance.

Posted by: Bobby at September 20, 2009 3:41 PM

Miki

That worked great....

Thanks
B

Posted by: BC at November 13, 2009 11:22 PM

Thanks Michael, this worked for me :)

Posted by: Spartan Pixel at December 13, 2009 12:11 PM

For the love of God, stop redirecting users. No one with an iPhone wants to look at a crappy mobile web site. If you must do this, please do the following:

1. Take us to the same page we were trying to reach, not the home page of your iPhone site; and

2. Give us a link to the full version so we have a choice.

Just know that when you redirect us, we end up going to the google caches version of the page we were trying to reach.

Posted by: iPhone user at December 18, 2009 7:20 PM

This is exactly the sort of info I required!

We are looking to have our comapny site more accessible to iPhone users and this has helped greatly.

Well done, Dave!

Posted by: Carlos McNabb at December 30, 2009 7:37 PM

Hey Dave (or other knowledgeable reader)Is there a way to load a different style sheet for iPhone users VS a redirect?

Posted by: Jim Walczak at January 5, 2010 1:41 AM

For future reference, I'm wondering if anyone has something similar to this written in php?

Posted by: Jamie at January 15, 2010 1:13 AM

To load a different style sheet for iphone rather than redirect, use this in php:

<link rel="stylesheet" type="text/css" href="<?php if (stristr($_SERVER['HTTP_USER_AGENT'], 'iphone')){echo 'iphone.css';} else{ echo 'default.css';}?>" />

Posted by: Alex at January 16, 2010 2:10 PM

How is everyone thinking? I believe everyone except one commenter just ignored the iPod Touch, you do understand its browser is exactly like the iPhone's, right?

<?php

if (preg_match("/iP(hone|od)/i", $_SERVER['HTTP_USER_AGENT'])) {
    // User has an iPhone/iPod
} else {
    // User has something else
}

?>

Posted by: mike at January 31, 2010 9:37 AM

Look the project called "Apache Mobile Filter", is the fast way to detect in any language a mobile device and to have easily its capabilities.

The url: www.apachemobilefilter.org

Posted by: Idel at February 8, 2010 4:03 AM

I have something to say, now that you mention it, but ...
Starbucks coffee cup I do have a lot to say, and questions of my own for that matter, but first I'd like to say thank you for all your efforts on this Web site by buying you a cup of coffee!

I do have a comment, now that you mention it!











Remember personal info?


Please note that I will never send you any unsolicited email. Ever.

While I'm at it, please note that by submitting a question or comment you're agreeing to my terms of service, which are: you relinquish any subsequent rights of ownership to your material by submitting it on this site.








Ask Dave Taylor: The iPhone App: Advertisement



Follow me on Twitter @DaveTaylor

Search
Find just the answers you seek from among our 2300+ free tech support articles by using our Lijit search engine.


Help!





Subscribe to
Ask Dave Taylor!

Add to Google Reader
Add to My Yahoo!
Subscribe in NewsGator Online

RDF   XML

Free Updates!
Sign up and get free weekly updates and special offers on books, seminars, workshops and more.


Recent Entries
Book Links
© 2002 - 2010 by Dave Taylor. All Rights Reserved.

Note: This web site is for the purpose of disseminating information for educational purposes, free of charge, for the benefit of all visitors. We take great care to provide quality information. However, we do not guarantee, and accept no legal liability whatsoever arising from or connected to, the accuracy, reliability, currency or completeness of any material contained on this web site or on any linked site.

[whiteboard marker tray]
"Ask Dave Taylor®" is a registered trademark of Intuitive Systems, LLC.