您如何使用 PHP 检测移动设备?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16754574/
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-25 11:39:15  来源:igfitidea点击:

How do you detect a mobile device with PHP?

phphtmlcssmobile

提问by Cory Nickerson

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?

检测移动设备最可靠、最有效的方法是什么?

回答by Frederico Schardong

You can use thisproject to do that:

你可以使用这个项目来做到这一点:

if ($detect->isMobile()) {
    // Any mobile device.
}

回答by argentum47

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

您可以获取服务器代理并使用 preg_match 进行检查。例如:

$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/");

回答by bizzehdee

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.

您可以尝试http://detectmobilebrowsers.com/库。有一段代码来检测移动浏览器几乎所有你需要能够检测移动浏览器的东西。

回答by Sam

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

我建议使用此类进行良好且完整的移动检测php-mobile-detect

or you must filter the user agent

或者您必须过滤用户代理