Organizational Research By

Surprising Reserch Topic

Question:PHP: Detect Mobile User Agent Using preg_match Regular Expression


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. $mobile_agents = '!(tablet|pad|mobile|phone|symbian|android|ipod|ios|blackberry|webos)!i'; if(preg_match($mobile_agents, $_SERVER['HTTP_USER_AGENT'])) { // Mobile! }

asked Sep 13, 2013 in Java Interview Questions by anonymous
edited Sep 12, 2013
0 votes
79 views



Related Hot Questions

4 Answers

0 votes
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;
answered Sep 13, 2013 by anonymous
edited Sep 12, 2013
0 votes
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; } }
answered Sep 13, 2013 by anonymous
edited Sep 12, 2013

...