Home / Developer Tools / Documentation / Tutorials / Developer Resources / User Agent Detection

User Agent Detection

Sometimes with Drupal it is beneficial to know how your users are accessing your site. Finding out what browser is being used can affect the features you are able to use and whether the user is on a desktop, mobile phone, or tablet can affect how you theme the page they are viewing. One way to do this is to get the user agent and check for certain information.

In a module you can write code for

$user_agent = $_SERVER['HTTP_USER_AGENT'];

This will give you a string containing information about your browser. For example, accessing the user agent string from a MacBook Pro coming from Google Chrome you get the string

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22

Which tells us information about the operating system, the browser, and the browser version. However, if we access this from an Android phone we get

Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; ADR6300 Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

Using this string we can detect if it contains Android using

preg_match("/Android/i", $user_agent)

since the user agent string contains "Android" it will match and we can then change theming knowing that they are coming from mobile, or we can load content that is specific to Android for accessing phone data. It also contains the version of Android that the phone is running (2.3.4 in this case) which can be used to find out what options you have available.

From an iPad the user string looks like this

Mozilla/5.0 (iPad; CPU OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3

Using this we can detect if we are on either an iPad specifically or any apple device in general using

preg_match("/iPhone|iPad|iPod/i", $user_agent)

which in this case will match on the iPad portion of the string. This can allow us to load apple specific code and if we detect for iPad specifically we can change the theming to a tablet variation.

Detecting the user agent can occasionally be tricky as not every browser and device identifies exactly as expected. However, at the moment matching on a fragment of the user agent string seems to be the best solution catching the majority of cases and special exceptions can be made as necessary. There are some issues as well with agents identifying as more than just a single browser, as you can see in the first string, Chrome will also identify as others. If you need to specifically switch on that browser you will need to do more research to find what set of strings is most likely to give you valid information.