Recognizing the iPhone for webpages

As said in my 2009 predictions, the iPhone, and other mobile devices, will get a larger share in the tools your visitors use to visit your websites. So I suppose you will not be surprised when I tell you that it is very important to sure that your website is ready to receive your mobile customers.

The first step in this, is to let your webpage recognize if it is being visited by an iPhone. The best way to do this is by checking on the “user agent string”. For the not-knowers: this is a string of information of itself and its system that the browser sends to the webserver. In case of an iPhone, the user agent string looks something like this, depending on the language, the firmwareversion, and the country of origin:

– Mozilla/5.0 (iPhone; U; XXXXX like Mac OS X; en) AppleWebKit/420+(KHTML, like Gecko) Version/3.0 Mobile/241 Safari/419.3

– Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+(KHTML, like Gecko) Version/3.0 Mobile/21A537a Safari/419.3

This user agent string can easily be used to detect if your webpage visitor is using an iPhone or a regular browser. The following short pieces of code return the user agent string, and show it in your webpage:

JavaScript:

<script type=”text/javascript”>

document.write(navigator.userAgent);

</script>

ASP:

<%=Request.ServerVariables(“HTTP_USER_AGENT”)%>

PHP:

<?php

eco $_SERVER[‘HTTP_USER_AGENT’];

?>

As you may or may not know, once you can determine the type of browser being used, it is rather simple to forward Mobile Safari to the correct, iPhone optimized index page (perhaps called iphone_index.html or something):

Javascript:

<html>

<head>

<script type=”text/javascript”>

window.onload=function(){

var agent=navigator.userAgent.toLowerCase();

var is_iphone=agent.indexOf(“ipone”) !=-1;

if(is_iphone){

window.location=”iphone_index.html”

}else{

window.location=”other_index.html”;

}

}

</script>

<body>

</body>

</html>

ASP:

<%

useragent = Request.ServerVariables(“HTTP_USER_AGENT”)

if instr(useragent, “iphone”) > 0 then

response.redirect(“iphone_index.html”)

else

response.redirect(“regular_index.html”)

end if

%>

PHP:

<?php

$useragent= $_SERVER[‘HTTP_USER_AGENT’];

if(strpos($useragent, ‘iphone’ > 0) {

header(“Location: iphone_index.html”);

}else{

header(“Location: regular_index.html”);

}

?>

Of course, once you have this script in one of these languages to check if it is an iPhone, it can easily be extended to check for other types of browsers, and create optimized indexpages for those too.

Happy coding! 😉

Leave a Comment





Pin It on Pinterest

Share This

Share This

Share this post with your friends!

%d bloggers like this: