PHP: Detect Mobile User Agent Using preg_match Regular Expression
Please note that this post is over a year old and may contain outdated information.
Using PHP, you can change the whole site or redirect users to a different site when they browse from a mobile device, or just change the CSS.
This method relies on the HTTP_USER_AGENT value in the $_SERVER super global. Since this value ultimately comes from the client's browser, it can be spoofed, though don't expect a large portion of visitors to know how.
Here is a very basic example of detecting if a user is browsing on a mobile device using PHP preg_match:
For those unfamiliar with regular expressions, this simply checks to see if any of the values, separated by the "|" (pipe) character, are present in the user agent string. The "i" at the end means it is case-insensitive. You can also use a non-regex function such as strpos if you want.
Since it is possible that HTTP_USER_AGENT doesn't exist, and you may want to tweak various parts of your page when mobile is detected, I suggest doing something like this instead:
You can also compress it down to one line like this, using a ternary comparison operator:
This method relies on the HTTP_USER_AGENT value in the $_SERVER super global. Since this value ultimately comes from the client's browser, it can be spoofed, though don't expect a large portion of visitors to know how.
How to do it
Here is a very basic example of detecting if a user is browsing on a mobile device using PHP preg_match:
$mobile_agents = '!(tablet|pad|mobile|phone|symbian|android|ipod|ios|blackberry|webos)!i';
if (preg_match($mobile_agents, $_SERVER['HTTP_USER_AGENT'])) {
// Mobile!
}
For those unfamiliar with regular expressions, this simply checks to see if any of the values, separated by the "|" (pipe) character, are present in the user agent string. The "i" at the end means it is case-insensitive. You can also use a non-regex function such as strpos if you want.
A more complete example
Since it is possible that HTTP_USER_AGENT doesn't exist, and you may want to tweak various parts of your page when mobile is detected, I suggest doing something like this instead:
$mobile = false;
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$mobile_agents = '!(tablet|pad|mobile|phone|symbian|android|ipod|ios|blackberry|webos)!i';
if (preg_match($mobile_agents, $_SERVER['HTTP_USER_AGENT'])) {
$mobile = true;
}
}
You can also compress it down to one line like this, using a ternary comparison operator:
$mobile = isset($_SERVER['HTTP_USER_AGENT']) && preg_match('!(tablet|pad|mobile|phone|symbian|android|ipod|ios|blackberry|webos)!i', $_SERVER['HTTP_USER_AGENT']) ? true : false;