2

I'm looking for the best method/practice to use for detecting if a person is using a mobile device to view a website. I'd like to be able to adjust the templates of the website if a mobile device is detected so it's easier to view.

What is the most reliable and effective method for detecting mobile devices?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Cory Nickerson
  • 883
  • 2
  • 11
  • 19
  • 1
    Please be polite. His edit was perfectly fine; see [the relevant FAQ section](http://stackoverflow.com/faq#editing). – Ry- May 25 '13 at 23:59

4 Answers4

5

You can use this project to do that:

if ($detect->isMobile()) {
    // Any mobile device.
}
Frederico Schardong
  • 1,946
  • 6
  • 38
  • 62
4

you can get the server agent and use a preg_match to check it. for example:

$isMobile=(bool)preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);

i got a better version of the code from here:

$isMobile = (bool)preg_match('#\b(ip(hone|od|ad)|android|opera m(ob|in)i|windows (phone|ce)|blackberry|tablet'.
                    '|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp|laystation portable)|nokia|fennec|htc[\-_]'.
                    '|mobile|up\.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\b#i', $_SERVER['HTTP_USER_AGENT'] );

and then you can :

if(isMobile())
    header("Location: http://m.site.com/");
Community
  • 1
  • 1
argentum47
  • 2,385
  • 1
  • 18
  • 20
3

you could try the http://detectmobilebrowsers.com/ libraries. has a piece of code to detect mobile browsers for almost everything you would need to be able to detect mobile browsers.

bizzehdee
  • 20,289
  • 11
  • 46
  • 76
2

I suggest of use this class for a good and complete mobile detection php-mobile-detect

or you must filter the user agent

Sam
  • 2,950
  • 1
  • 18
  • 26
  • Is such a large script necessary to detect a mobile device? Seems like their methods depend on individual models of phones and their operating systems which are always changing. I wont want to have to update my software like every 3 days with the rate new phones come out. – Cory Nickerson May 25 '13 at 22:52
  • @CoryNickerson if you want a good script, that is the best actually, otherwise you must do all manually filtering the user agent from php – Sam May 25 '13 at 22:54