13

I am writing a website with PHP. Since it will need to be accessed by anyone on the network to access the internet I have to create a mobile version. How do I best check if it's a mobile device? I don't want to have a switch statement with 50 devices at the end since I don't only want to support the iPhone.

Is there a PHP class I could use?

John Topley
  • 113,588
  • 46
  • 195
  • 237
Thomaschaaf
  • 17,847
  • 32
  • 94
  • 128

11 Answers11

15

You need to check several headers that the client sends, such as USER_AGENT and HTTP_ACCEPT. Check out this article for a comprehensive detection script for mobile user-agents in PHP.

Eran Galperin
  • 86,251
  • 24
  • 115
  • 132
5

You should look at Tera-WURFL, it is a PHP & MySQL-based software package that detects mobile devices and their capabilities. Here is the Tera-WURFL code that you would use to detect if the visiting device is mobile:

<?php
require_once("TeraWurfl.php");
$wurflObj = new TeraWurfl();
$wurflObj->GetDeviceCapabilitiesFromAgent();
if($wurflObj->capabilities['product_info']['is_wireless_device']){
    // this is a mobile device
}else{
    // this is a desktop device
}
?>    
Steve Kamerman
  • 146
  • 1
  • 1
4

Another thing to consider: A lot of sites will actually offer a different URL for mobile devices. See http://m.facebook.com as an example. With the increasing ability of devices these days, this gives your users an option. If they're on a device which can actually handle a full website nicely (using zooming and whatnot), then they'd probably get pretty annoyed being forced into a particular layout.

nickf
  • 537,072
  • 198
  • 649
  • 721
3

For the redirection part, I used

$arr = explode('.', $_SERVER['SERVER_NAME'], 2);
$sub=$arr[0];
$need_redirect=false;
if (!isset($_SERVER['HTTP_REFERER'])){
    $need_redirect=true;
}else{
    $domain = parse_url($_SERVER['HTTP_REFERER']);   
    $host = $domain['host'];
    if (!preg_match('/romajidesu\.com/', $host)){
        $need_redirect=true;        
    }    
}
if ($need_redirect && ($sub!='m') && is_mobile() ){
    $old_url=$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; 
    $new_url='http://'.str_replace('www.', 'm.', $old_url);
    header("Location:".$new_url);die();
}

For more detail of my implmentation, please read my blog at http://haibuihoang.blogspot.com/2012/11/how-to-redirect-mobile-users-to-your.html

haibuihoang
  • 171
  • 10
2

Traditionally mobile devices have been detected by comparing the HTTP User-Agent header against a list of well known mobile UA strings. A novel approach instead tries to detect the presence of a desktop OS - anything which is found to not be a desktop OS must then be mobile.

This results in far less false positives.

I've written a post with sample code in Python here: http://notnotmobile.appspot.com

Here is a snippet:

import re

# Some mobile browsers which look like desktop browsers.
RE_MOBILE = {
    "iphone" : re.compile("ip(hone|od)", re.I),
    "winmo" : re.compile("windows\s+ce", re.I)}

RE_DESKTOP = {
    "linux" : re.compile(r"linux", re.I),
    "windows" : re.compile(r"windows", re.I),
    "mac" : re.compile(r"os\s+(X|9)", re.I),
    "solaris" : re.compile(r"solaris", re.I),
    "bsd" : re.compile(r"bsd", re.I)}

# Bots that don't contain desktop OSs.
RE_BOT = re.compile(r"(spider|crawl|slurp|bot)")


def is_desktop(user_agent):
  # Anything that looks like a phone isn't a desktop.
  for regex in RE_PHONE.values():
    if regex.search(user_agent) is not None:
      return False

  # Anything that looks like a desktop probably is.
  for regex in RE_DESKTOP.values():
    if regex.search(user_agent) is not None:
      return True

  # Bots get the desktop view.
  if RE_BOT.search(user_agent) is not None:
    return True

  # Anything else is probably a phone!
  return False

def get_user_agent(request):
  # Some browsers put the User-Agent in a HTTP-X header
  if 'HTTP_X_OPERAMINI_PHONE_UA' in request.headers:
    return request.headers['HTTP_X_OPERAMINI_PHONE_UA']
  elif:
    # Skyfire / Bolt / other mobile browsers
    ...
  else:
    return request.headers.get('HTTP_USER_AGENT', '')

def view(request):
  user_agent = get_user_agent(request)
  if is_desktop(user_agent):
    return desktop_response()
  else:
    return mobile_response()
jb.
  • 9,987
  • 12
  • 39
  • 38
1

Would the user agent in the request give you enough info to make a decision?

There is a good list of user agents here.

scunliffe
  • 62,582
  • 25
  • 126
  • 161
0

It's not the best option to decide mobile device by checking user agent. You should join javascript device width check with PHP user agent check. But up to some point user agent check is acceptable.

I use this. Not as good as WURFL, but solves my issues easily:

function is_mobile_device() {

    $agent=$_SERVER['HTTP_USER_AGENT'];

    if( strpos($agent,"Android") !== FALSE
        || strpos($agent,"IOS") !== FALSE
        || strpos($agent,"iPhone") !== FALSE
        || strpos($agent,"iPad") !== FALSE
        || strpos($agent,"iPod") !== FALSE
        || strpos($agent,"Symbian") !== FALSE
        || strpos($agent,"BlackBerry") !== FALSE
        || strpos($agent,"Opera Mini") !== FALSE
    ) {
        return TRUE;
    }
    return FALSE;

}
trante
  • 33,518
  • 47
  • 192
  • 272
0

For detection based on User-Agent, use WURFL database. At least it's comprehensive and continually updated.

If you target only high-end(ish) phones, then you may not need to detect them at all, just embed appropriate mobile stylesheets.

Community
  • 1
  • 1
Kornel
  • 97,764
  • 37
  • 219
  • 309
0

If you want adapt the content to any particular device e.g. to resize images to be the width of the device, then you can also use DeviceAtlas. Based on the useragent of the requesting device, it will tell you the size of the screen, along with supported image formats, supported markup types, maximum page size and so on.

0

Most mobile websites use the user_agent exclusively. An opensource database of device capabilities is maintained at http://wurfl.sourceforge.net/ Using wurlf, and based on the user_agent, you can identify the screen physical and pixel width, length, and many more parameters, and make your rendering decision.

Yaniv
  • 141
  • 4
0

What is a mobile device? Weaker CPU? Lower bandwidth? In reality, it has a screen the resolution of which is below 320x240 and color depth is below 24.

You have to use Javascript also. This link will give you an idea: http://www.w3schools.com/js/tryit.asp?filename=tryjs_browsermonitor

And, this link will teach you what is what: http://www.w3schools.com/htmldom/dom_obj_screen.asp

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
yogman
  • 4,021
  • 4
  • 24
  • 27