H3XED
Programming   Browse Other Topics

PHP: Detect Mobile User Agent Using preg_match Regular Expression

by Nick Vogt - Mar 23, 2012 - Want a more reliable way to detect mobile visitors than the CSS media query? 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. I wrote a post on how to spoof your user agent on Android for those curious.


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 "|" (or) 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:

isset($_SERVER['HTTP_USER_AGENT']) && preg_match('!(tablet|pad|mobile|phone|symbian|android|ipod|ios|blackberry|webos)!i', $_SERVER['HTTP_USER_AGENT']) ? $mobile = true : $mobile = false;
Topic  Programming    Tags  php
Share on

Comments


© Nick VogtRSSDisclosure PolicyPrivacy Policy@Facebook@Twitter