Handling Code for Distinguishing Between iOS and Android
This guide covers PHP code to check whether the current mobile device is running on iOS or Android.
This can be useful for websites that provide specific operating system-based features in a mobile environment or offer different experiences to iOS and Android users.
Note!
The methods discussed here for checking mobile environments and determining whether a device is running on iOS or Android may have limitations in terms of accuracy and scalability; therefore, their accuracy or scalability cannot be guaranteed or warranted. Accordingly, before relying on any materials or examples, you must carefully test and review them based on your own judgment to ensure they are free from errors, bugs, or vulnerabilities.
Functions for Distinguishing Between Mobile iOS and Android
Detecting iOS and Android on mobile devices using PHP is one of the tasks frequently required in web development. This distinction is necessary to provide an appropriate environment whenever a user accesses the site from a mobile device. In this post, we will introduce methods for detecting mobile devices with PHP and, specifically, distinguishing between iOS and Android.
Function Code for Distinguishing Between Mobile iOS and Android
/**
* A polyfill function for the str_contains() function introduced in PHP 8.
* Used to support str_contains() in PHP versions prior to 8.
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for.
* @return bool Returns true if the substring is found in the given string, false otherwise.
*/
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.
* 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 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 identified as mobile.
// 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 find 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 non-mobile.
return false;
}
}
/**
* A function to detect and check for iOS.
*
* @return bool Returns true if the mobile device is iOS, false otherwise.
*/
function is_ios() {
return is_mobile() && preg_match('/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT']);
}
/**
* A function to detect and check for Android.
*
* @return bool Returns true if the mobile device is Android, false otherwise.
*/
function is_android() {
return is_mobile() && preg_match('/Android/', $_SERVER['HTTP_USER_AGENT']);
}
/* Execute different code based on whether the device is iOS or Android. */
if (is_ios()) {
// Code for the iOS environment
} elseif(is_android()) {
// Code for the Android environment
} else {
// Code for other environments
}
The following are the primary functions used in the code above:
The following is a brief explanation of the code's execution flow.
- Polyfill for the
str_contains()function:
A polyfill function is defined to enable the use of thestr_contains()function, introduced in PHP 8, in versions prior to PHP 8. This function checks whether a specific substring is included within a string and is utilized within the mobile device detection function. - Mobile device detection function (
is_mobile()):
This function determines whether a device is mobile by checking theHTTP_SEC_CH_UA_MOBILEheader or analyzing theHTTP_USER_AGENT. It returnstruefor mobile devices andfalseotherwise. - Functions for distinguishing iOS and Android (
is_ios()andis_android()):
Once a mobile device is detected, these functions determine whether the device is running iOS or Android. For iOS, it checks if strings such as 'iPad', 'iPod', or 'iPhone' are present in theHTTP_USER_AGENT. For Android, it identifies the device by checking for the 'Android' string. - Environment branching using conditional statements:
Anif-elseif-elseconditional statement is used to execute different code based on the detected environment. If an iOS environment is detected, the code designated for iOS is executed; if Android is detected, the corresponding Android code runs. Otherwise, the code for other environments is executed. These conditional statements can be conveniently modified based on your development environment or specific requirements.
Limitations of the Example Code
Through this process, the provided code offers useful functionality to distinguish between iOS and Android on mobile devices using PHP and to perform operations suitable for each environment. However, the example code above has several limitations, including the following:
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.