如何确定它是否是带有PHP的移动设备?

时间:2023-01-22 07:21:49

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.

我正在用PHP编写一个网站。由于网络上的任何人都需要访问它才能访问互联网,因此我必须创建一个移动版本。如何最好地检查它是否是移动设备?我不想在最后有50个设备的switch语句,因为我不仅要支持iPhone。

Is there a PHP class I could use?

有没有我可以使用的PHP类?

11 个解决方案

#1


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.

您需要检查客户端发送的多个标头,例如USER_AGENT和HTTP_ACCEPT。查看本文,了解PHP中移动用户代理的综合检测脚本。

#2


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:

您应该看看Tera-WURFL,它是一个基于PHP和MySQL的软件包,可以检测移动设备及其功能。以下是您将用于检测访问设备是否为移动设备的Tera-WURFL代码:

<?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
}
?>    

#3


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.

另一件需要考虑的事情是:许多网站实际上会为移动设备提供不同的URL。以http://m.facebook.com为例。随着设备日益增长的能力,这为您的用户提供了一个选择。如果他们在一个可以很好地处理完整网站的设备上(使用缩放等等),那么他们可能会非常生气*进入特定的布局。

#4


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

有关我的详细信息,请阅读我的博客http://haibuihoang.blogspot.com/2012/11/how-to-redirect-mobile-users-to-your.html

#5


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.

传统上,通过将HTTP User-Agent标头与众所周知的移动UA字符串列表进行比较,检测到移动设备。一种新颖的方法试图检测桌面操作系统的存在 - 任何被发现不是桌面操作系统的东西都必须是移动的。

This results in far less false positives.

这导致误报率低得多。

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

我在这里用Python编写了一个包含示例代码的帖子: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()

#6


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.

这里有一个很好的用户代理列表。

#7


0  

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

对于基于User-Agent的检测,请使用WURFL数据库。至少它是全面的,不断更新的。

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

如果您只定位高端(ish)手机,那么您可能根本不需要检测它们,只需嵌入适当的移动样式表即可。

#8


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.

如果您想要将内容调整到任何特定设备,例如要将图像大小调整为设备的宽度,您还可以使用DeviceAtlas。根据请求设备的使用者,它将告诉您屏幕的大小,支持的图像格式,支持的标记类型,最大页面大小等。

#9


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.

大多数移动网站都使用user_agent。设备功能的开源数据库保存在http://wurfl.sourceforge.net/使用wurlf,基于user_agent,您可以识别屏幕物理和像素宽度,长度和更多参数,并做出渲染决策。

#10


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.

什么是移动设备? CPU较弱?带宽较低?实际上,它的屏幕分辨率低于320x240,色深低于24。

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

你也必须使用Javascript。这个链接会给你一个想法: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

而且,这个链接将教你什么是:http://www.w3schools.com/htmldom/dom_obj_screen.asp

#11


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.

通过检查用户代理来决定移动设备不是最好的选择。您应该使用PHP用户代理检查加入javascript设备宽度检查。但是在某些时候用户代理检查是可以接受的。

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

我用这个。不如WURFL,但很容易解决我的问题:

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;

}

#1


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.

您需要检查客户端发送的多个标头,例如USER_AGENT和HTTP_ACCEPT。查看本文,了解PHP中移动用户代理的综合检测脚本。

#2


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:

您应该看看Tera-WURFL,它是一个基于PHP和MySQL的软件包,可以检测移动设备及其功能。以下是您将用于检测访问设备是否为移动设备的Tera-WURFL代码:

<?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
}
?>    

#3


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.

另一件需要考虑的事情是:许多网站实际上会为移动设备提供不同的URL。以http://m.facebook.com为例。随着设备日益增长的能力,这为您的用户提供了一个选择。如果他们在一个可以很好地处理完整网站的设备上(使用缩放等等),那么他们可能会非常生气*进入特定的布局。

#4


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

有关我的详细信息,请阅读我的博客http://haibuihoang.blogspot.com/2012/11/how-to-redirect-mobile-users-to-your.html

#5


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.

传统上,通过将HTTP User-Agent标头与众所周知的移动UA字符串列表进行比较,检测到移动设备。一种新颖的方法试图检测桌面操作系统的存在 - 任何被发现不是桌面操作系统的东西都必须是移动的。

This results in far less false positives.

这导致误报率低得多。

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

我在这里用Python编写了一个包含示例代码的帖子: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()

#6


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.

这里有一个很好的用户代理列表。

#7


0  

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

对于基于User-Agent的检测,请使用WURFL数据库。至少它是全面的,不断更新的。

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

如果您只定位高端(ish)手机,那么您可能根本不需要检测它们,只需嵌入适当的移动样式表即可。

#8


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.

如果您想要将内容调整到任何特定设备,例如要将图像大小调整为设备的宽度,您还可以使用DeviceAtlas。根据请求设备的使用者,它将告诉您屏幕的大小,支持的图像格式,支持的标记类型,最大页面大小等。

#9


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.

大多数移动网站都使用user_agent。设备功能的开源数据库保存在http://wurfl.sourceforge.net/使用wurlf,基于user_agent,您可以识别屏幕物理和像素宽度,长度和更多参数,并做出渲染决策。

#10


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.

什么是移动设备? CPU较弱?带宽较低?实际上,它的屏幕分辨率低于320x240,色深低于24。

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

你也必须使用Javascript。这个链接会给你一个想法: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

而且,这个链接将教你什么是:http://www.w3schools.com/htmldom/dom_obj_screen.asp

#11


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.

通过检查用户代理来决定移动设备不是最好的选择。您应该使用PHP用户代理检查加入javascript设备宽度检查。但是在某些时候用户代理检查是可以接受的。

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

我用这个。不如WURFL,但很容易解决我的问题:

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;

}