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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/386046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:34:30  来源:igfitidea点击:

How do I determine whether it's a mobile device with PHP?

phpmobile

提问by Thomaschaaf

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 类吗?

回答by Eran Galperin

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

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

回答by Steve Kamerman

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

回答by nickf

Another thing to consider: A lot of sites will actually offer a different URL for mobile devices. See http://m.facebook.comas 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为例。随着如今设备能力的增强,这为您的用户提供了一个选择。如果他们使用的设备实际上可以很好地处理整个网站(使用缩放等),那么他们可能会因为被迫进入特定布局而感到非常恼火。

回答by haibuihoang

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

回答by jb.

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: //notmobile.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()

回答by scunliffe

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

请求中的用户代理会为您提供足够的信息来做出决定吗?

There is a good list of user agents here.

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

回答by Kornel

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)手机,那么您可能根本不需要检测它们,只需嵌入适当的移动样式表即可

回答by Kornel

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。根据请求设备的用户代理,它会告诉您屏幕的大小,以及支持的图像格式、支持的标记类型、最大页面大小等。

回答by Yaniv

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,您可以识别屏幕物理和像素宽度、长度和更多参数,并做出您的渲染决策.

回答by yogman

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