Handling Code for Mobile Detection
This guide covers PHP code for checking whether the current device is running on a mobile platform, such as a smartphone or tablet.
The code for mobile detection will be structured as a function. This function is suitable for identifying mobile devices, which can be useful for websites that provide specific features for mobile environments or offer different experiences to mobile and desktop users.
Note!
The functions for mobile detection discussed here may have limitations in terms of accuracy and scalability; therefore, their performance or reliability cannot be guaranteed. Accordingly, you should carefully test and review all materials and examples for errors, bugs, or vulnerabilities based on your own judgment before relying on them.
Mobile Detection Function
Considering the user environment of a web application is crucial when writing code. In particular, it is necessary to account for mobile device usage. To achieve this, we will create a function for checking whether a device is a mobile device using PHP.
irst, in PHP, user agent information can be verified through the HTTP_USER_AGENT header sent from the user's web browser. Based on this information, it is possible to determine whether the device is a mobile device. Additionally, since PHP 8, the str_contains() function has been introduced, making it simple to check whether a specific string is included. However, since this function is not available in environments below PHP 8, we will also provide a polyfill function to replace it.
Code for the Mobile Detection Function
/**
* A polyfill function for str_contains(), which was introduced in PHP 8.
* This function allows the use of str_contains() in PHP versions below 8.
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for.
* @return bool Returns true if the given string contains the substring; otherwise, returns false.
*/
if (!function_exists('str_contains')) {
/*
* Polyfill for the str_contains() function.
* Source: https://core.trac.wordpress.org/browser/trunk/src/wp-includes/compat.php#L423
*/
function str_contains($haystack, $needle) {
if ('' === $needle) {
return true;
}
return false !== strpos($haystack, $needle);
}
}
/**
* A function to detect and check for mobile devices.
* It determines whether a device is mobile by checking the HTTP_SEC_CH_UA_MOBILE header
* and analyzing the HTTP_USER_AGENT.
*
* @return bool Returns true if a mobile device is detected; otherwise, returns false.
*/
function is_mobile() {
if (isset($_SERVER['HTTP_SEC_CH_UA_MOBILE'])) {
// If the HTTP_SEC_CH_UA_MOBILE header exists and its value is '?1', it is considered a mobile device.
// Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA-Mobile
return ( '?1' === $_SERVER['HTTP_SEC_CH_UA_MOBILE'] );
} elseif (!empty($_SERVER['HTTP_USER_AGENT'])) {
// Analyzes the HTTP_USER_AGENT to identify mobile characteristics.
$user_agent = $_SERVER['HTTP_USER_AGENT'];
return str_contains($user_agent, 'Mobile')
|| str_contains($user_agent, 'Android')
|| str_contains($user_agent, 'Silk/')
|| str_contains($user_agent, 'Kindle')
|| str_contains($user_agent, 'BlackBerry')
|| str_contains($user_agent, 'Opera Mini')
|| str_contains($user_agent, 'Opera Mobi');
} else {
// If neither the HTTP_SEC_CH_UA_MOBILE header nor the HTTP_USER_AGENT is present,
// it is considered a non-mobile device.
return false;
}
}
/* Execute different code depending on whether the device is mobile. */
if(is_mobile()) {
// Code for mobile environments
} else {
// Code for desktop environments
}
The code above provides a simple function for detecting and checking for mobile devices in PHP. However, please be sure to review the limitations of the example code provided.
Limitations of the Example Code
The example code provided has several limitations. These include the following points:
Limitations of HTTP_USER_AGENT
Detecting mobile devices by analyzing the User-Agent string can be unreliable. Users can manually change their mobile browsers to "Desktop Mode." Therefore, this code has inherent limitations regarding the User-Agent. Furthermore, if client-side information is utilized for security-related purposes, additional appropriate measures are required.
Scalability Regarding New Mobile Devices
The code analyzes the HTTP_USER_AGENT header to detect mobile devices. Whenever a new mobile device is released, the code must be updated to account for that device's User-Agent string pattern. This may require ongoing maintenance as new mobile devices are introduced.
Inconsistency of Cached User-Agent Values
When caching is applied, issues may arise when multiple users with the same User-Agent value access the site from different devices. If a cached User-Agent value remains fixed, it may not return the correct results for access from new devices or browsers. This can degrade the user experience and provide incorrect results.
Therefore, when implementing a cache, care must be taken to ensure that User-Agent values are not cached. Instead, the cache should be configured using a stable method for identifying users.