Archive for February, 2009

Better iPhone User Agent Regex

Feb 19 2009 Published by Brad Kellett under Web Development

David Walsh recently published a blog post detailing how to detect iPhone and iPod Touch users on your website via the user agent string, and while the concept is fine, I much prefer a slightly different method using regex to do the detection. In PHP:

  1. if(preg_match(‘/Apple.*Mobile.*Safari/’, $_SERVER[‘HTTP_USER_AGENT’])  {  
  2.     header(‘Location: http://yoursite.com/iphone’);  
  3.     exit();  
  4. }

Using this regex, you are not only covered for the iPhone and iPod Touch (in one call, even), but also potentially for any future Apple mobile devices.

And for those interested, the actual user agents for the iPhone and iPod Touch are variations of:

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

View Comments