Display different website on iphone by detecting the device’s user agent browser

I am currently building a site for a client and they want a slightly different or simplified version of their site on iphone.  In order to achieve this we must detect what is called the “user agent” or the type of device accessing the website through the browsers they are using.

I am building the site in PHP so here’s what I do:

//function to detect if an iphone has accessed the webpage
function isiPhone()
{
  $user_agent = $_SERVER['HTTP_USER_AGENT']; //get the user agent

  if(preg_match('/iphone/i',$user_agent)) //find this string in the UA
  {
    return true; //return true if found
  }
  return false; //otherwise return false
}

If you want to make the function more specific to find user agents from other browsers e.g. preg_match(‘/android/i’,$user_agent) will find android devices.

Once you’ve detected the device you would then redirect the user to a different version of the site for mobile consumption.

Hope this helps :-)

Leave a Reply

Your email address will not be published. Required fields are marked *