Mobile device detection using PHP and USER-Agent

When designing responsive websites, the main focus is using the template framework which has been chosen for the site, eg bootstrap to create views for different devices. This works to a certain extent but also creates a lot of code bloat which may load unnecessarily. 

But what if you did not want to use bootstrap and use a method which identified the actual device? This is where the USER-Agent variable can help. This is available in PHP.


A simple method to determine if the user is using a mobile is to call a function similar to this.

// create function to determine user-agent
function isMobileDevice9() {
  return preg_match("/(android|mobile|mini|phone|tablet)/i", $_SERVER["HTTP_USER_AGENT"]);

The above code checks to see if the user-agent matches android, mobile, mini, phone and tablet. This then allows you to add if statements in your code. 

 // code for mobile
 // code for desktop

There are some limitations, such as some devices act like a mobile when in fact they are not, so determining what these edge cases could be would need some research.

Click here to view some of the most common user-agents.