iPhone and iPod CSS detection using PHP by AB

Daniel Scott of SneakyWeaselStudios.com asked how to create a Website for iPhone. It inspired me to post this code. This will allow you to specify two CSS stylesheets. One for the iPhone or iPod touch. The other for a regular Web browser. PHP is used to dectect whether or not the user is on an iPhone/iPod touch. This can be done using a media variable, instead, as Apple's documentation shows, but older browsers do not understand that code. So, I am proposing a PHP method instead.

This site is iPhone and iPod touch compatible.
http://www.albinoblacksheep.com/tutorial/iphone-ipod-css -->

One user agent string is for iPhone specifically, and the other is for iPod touch specifically. Incase you may want to target them differently. For example, you may need to only display telephone and SMS links for iPhone that would be useless on iPod touch.

<!-- First, detect the iPhone or iPod useragent using PHP -->

if (ereg('iPhone',$_SERVER['HTTP_USER_AGENT'])) {
$iphone = 1;
elseif (ereg('iPod',$_SERVER['HTTP_USER_AGENT'])) {
$iphone = 1;
else {
$iphone = 0;

<!-- If it's an iPhone, show the Viewport Meta tag and iPhone CSS -->
<!-- I left the 'if not IE' parts in from before I added PHP to this. You can remove them if you'd like. -->

<?php if ($iphone == '1'): ?>
<![if !IE]>
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<link rel="stylesheet" type="text/css" href="iphone.css" media="only screen and (max-device-width: 480px)"
charset="utf-8" />

<!-- If it's NOT an iPhone, show the normal CSS and no Viewport Meta tag -->

<?php else: ?>
<style type="text/css" media="screen, projection, tv"><!--
@import url("normal.css");
<?php endif; ?>

This tutorial is a work in progress, and more information is to come.

March 4, 2008