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:
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:
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 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:
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:
<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.
44 thoughts on “How do I detect an iPhone user coming to my site?”
I have a much more efficient solution. Detects all mobile users in 547 bytes. That’s iphone, ipad, sidekicks, black berrys, tablets, palmos, everything….
“Detect a mobile device with PHP in 547 bytes”
http://www.justindocanto.com/scripts/detect-a-mobile-device-in-php-using-detectmobiledevice
I think the USER_AGENT has changed to:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2
which no longer has the “iPhone” string in it – so your suggestion now fails. Do you have a recommendation on how to detect it now?
Maybe check for both “Mozilla” and “Gecko” and “Chrome” and “Safari” all present? It sure would be nice if they would just standardize it and mention “mobile” or put “iphone” back in…
Thanks, Dave!
<script language=javascript>
<!–
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
{
location.replace(“iphone-version.html”);
}
–>
</script>
Will this work for Ipad? Thanks!!
hi dave,
i’m a c# programmer i’m developing Mobile Application Builder once the user selected template for his site i have to show how its looks in iphone Exactly, i searched for simulator which can embed with the My webpage as part of the Application but i couldn’t get it ,i got only some simulators which is directly testing in their site ,so please help to find some iphone simulators which can embed and able to show preview in my site.
thanks in advance,
chandru.v
I put this at the beginning of my index.php:
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
{
var qes = confirm( “I have a site made for the iPhone. Click OK to visit it, or Cancel to go to the normal site.” );
if ( qes )
location.replace(“http://iphone-url/”);
}
Works as intended … but as my site is bilingual, I’d like to have this dialogue bilingual too … could I extend the script to detect the iPhone system language and put out the text accordingly? As in: if german, say “Hallo”, else say: “Hello” …
use CGI::Info;
my $info = CGI::Info->new();
if($info->is_mobile()) {
…..
}
And after you write on your css a specific class like this:
.iphone .myclass {}
here a other solution, all iPhone is javascript enable 🙂
–script–if (navigator.userAgent.toLowerCase().indexOf(‘iphone’)!=-1) document.documentElement.className+=’ iphone’; –/script–
Jules, many browsers now let you specify what browser you want to masquerade, but that’s not going to help you on your iPad. Even if you could spoof it, Google Docs just plain won’t work on the iPad within the browser. Search the iPad App Store, however, there are some third party solutions that give you access…
Michel, similarly, you should check that your browser isn’t set to report it’s a different program. Many browsers have a “Debug” menu, for example. Also look in the dusty corners of Preferences.
I am using a desktop but some site would notify that I am using a mobile browser and would prompt me to view the page in a mobile browser or a desktop browser.
Is it possible that my computer is hacked by some tech savvy voyeur?
Ok I have the reverse question. What if I want to spoof my http user agent?
Google docs will not let me edit my site from my iPad. Apple store peeps say it’s google blocking the iPad. Can I tack something on to my address to make google think I am using ie on a pc?
i am currently using for my website is
this is currently what i am using on PcsSite.Net it works great and i made that my self lol, well thank you a lot and i thought i share this little peice of code to you all
\\ read browser settings
$agent = $_SERVER[‘HTTP_USER_AGENT’];
\\ Browser settings found we need to find what type of browser it is so we move on to finding device name
\\ if iPhone is found we include a page for the iPhone browser
if (eregi(“iPhone”, $agent)) {
include(“iphone.php”);
}
\\ if Blackberry is found we include a page for the Blackberry browser
elseif (eregi(“BlackBerry”, $agent)) {
include(“blackberry.php”);
}
\\ if not a mobile browser we include our index page
else {
include(“index.php”);
}
thank you a lot and have a great day everyone and i hope this helps you in the near future
How do you detect the “white” shift key caps lock from the “blue” shift key caps lock for the iPhone? My detect caps lock JavaScript is flagging the white key and throwing up the warning prompt that’s supposed to be for when the caps lock key is enabled on a desktop.
Here is a PHP script that detects iphone visitors:
if(strpos($_SERVER[‘HTTP_USER_AGENT’], ‘iPhone’) ||
strpos($_SERVER[‘HTTP_USER_AGENT’], ‘iPod’)){
header(“Location: YOUR-MOBILE-URL”);
}
@walter, here is jQuery function that would help you to do that http://jquery-howto.blogspot.com/2010/09/iphone-ipod-detection-using-jquery.html
Is there anyway to make the website believe the iPhone is a computer?
I have a question about the other end- I want to hide the fact that I’m browsing on an iPhone. I want the website to believe that I am running on a PC so that I am never redirected, because I’m running a computer, I don’t want to go to a watered-down version of the site.
Do you know a way of hiding the iPhone information? I am not opposed to jailbreaking.
Thanks.
The right way to do it with some js is actually :
if(/iphone/i.test(navigator.userAgent)){ /*Execution here*/ }
You would rather use the test() method than the match() one.
The i flag is for case insensitive regular expression so don’t bother with some useless toLowerString().
That’s right, you only need a single line of code ^
How do I make a conditional statement that hides the contents of the tag from iPhone and iPod Touch users
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: http://www.apachemobilefilter.org
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
}
?>
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’;}?>” />
For future reference, I’m wondering if anyone has something similar to this written in php?
Hey Dave (or other knowledgeable reader)Is there a way to load a different style sheet for iPhone users VS a redirect?
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!
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.
Thanks Michael, this worked for me 🙂
Miki
That worked great….
Thanks
B
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.
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.
Excellent info. I’ll be trying this on my site for sure!
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.
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?
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.
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
Miki, that worked. Thanks.
<script language=javascript>
<!–
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
{
location.replace(“iphone-version.html”);
}
–>
</script>
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/” }
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/” }
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 */ }
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.
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
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?
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
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.