判断用户是否使用移动设备使用PHP浏览我的网站的最简单方法是什么?
我遇到过许多类,你可以使用,但我希望一个简单的if条件!
有什么办法可以让我这么做吗?
判断用户是否使用移动设备使用PHP浏览我的网站的最简单方法是什么?
我遇到过许多类,你可以使用,但我希望一个简单的if条件!
有什么办法可以让我这么做吗?
当前回答
您只需要包含user_agent.php文件,该文件可以在PHP页面中的移动设备检测中找到,并使用以下代码。
<?php
//include file
include_once 'user_agent.php';
//create an instance of UserAgent class
$ua = new UserAgent();
//if site is accessed from mobile, then redirect to the mobile site.
if($ua->is_mobile()){
header("Location:http://m.codexworld.com");
exit;
}
?>
其他回答
我编写这个脚本是为了用PHP检测移动浏览器。
该代码根据用户代理字符串通过preg_match()ing单词检测用户,这些单词在数百次测试后只在移动设备的用户代理字符串中找到。它在当前所有移动设备上都有100%的准确性,我目前正在更新它,以支持更多的移动设备。代码名为isMobile,如下所示:
function isMobile() {
return 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"]);
}
你可以这样使用它:
// Use the function
if(isMobile()){
// Do something for only mobile users
}
else {
// Do something for only desktop users
}
要将用户重定向到您的移动站点,我会这样做:
// Create the function, so you can use it
function isMobile() {
return 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"]);
}
// If the user is on a mobile device, redirect them
if(isMobile()){
header("Location: http://m.yoursite.com/");
}
我发现移动检测非常简单,你可以使用isMobile()函数:)
function isMobileDev(){
if(!empty($_SERVER['HTTP_USER_AGENT'])){
$user_ag = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(Mobile|Android|Tablet|GoBrowser|[0-9]x[0-9]*|uZardWeb\/|Mini|Doris\/|Skyfire\/|iPhone|Fennec\/|Maemo|Iris\/|CLDC\-|Mobi\/)/uis',$user_ag)){
return true;
};
};
return false;
}
一个更简单的解决方案似乎在大多数情况下都有效:
function funcDeviceType() {
// INFO ABOUT THE BROWSER/DEVICE USER IS VISITING ON
$useragent = $_SERVER["HTTP_USER_AGENT"];
if(stripos($useragent, "mobile")!== false){
return "mobile device";
}else{
return "desktop or laptop computer";
}
}
如果您的服务器支持get_browser(自PHP 4起可用),则非常简单。它们有一个内置的功能来满足你的要求。
参考:https://www.php.net/manual/en/function.get-browser.php
<?php
$browser = get_browser(null, true);
if($browser['ismobiledevice']) {
// Device is mobile
}
?>