[Drupal] How to detect mobile devices using PHP in Drupal backend?

| | 2 min read

My requirement was to detect the mobile devices from the drupal backend and redirect the user to the assigned URL. For this we needed to identify whether the user was accessing the site from a mobile device. For this we had to check the user agent string and compare that with the most common mobile devices. Then depending upon the condition we redirect the user to the corresponding URL.

Example code:

// Here we are getting the user agent from the browser.
if (array_key_exists('HTTP_USER_AGENT', $_SERVER)) {
  $user_agent = $_SERVER['HTTP_USER_AGENT']; 
}
else {
  $user_agent = "";
}

// Identifying if mobile or desktop.
// This is not mandatory. The URL for the mobile site are usually set with m. 
// eg: www.m.example.com. So if this url is selected on the mobile devices 
// then we do not need to check for user agent on those conditions
$server_name = $_SERVER['SERVER_NAME'];
$mob = explode('m.', $server_name);
if ($mob[1] != NULL) {
  $val = 'mobile';
}
else {
  $val = 'desktop';
  // Here user agent is checked with common mobile devices.
  // You can add more devices here.
  if (stripos($user_agent, 'ipod') || stripos($user_agent, 'iphone') ||   
      stripos($user_agent, 'ipad') || stripos($user_agent, 'android') || 
      stripos($user_agent, 'opera_mini') || stripos($user_agent, 'blackberry')) {
    $val = 'mobile';
    // Here you can write code to redirect user to the mobile url. 
    // Example url is www.m.example.com.
  }
}

This could also have happend on the front end using javascript but we had this particular case where we had to run this logic from the Drupal backend. Do note that there are also modules in Drupal that does browser detection from the backend.