判断用户是否使用移动设备使用PHP浏览我的网站的最简单方法是什么?

我遇到过许多类,你可以使用,但我希望一个简单的if条件!

有什么办法可以让我这么做吗?


当前回答

没有可靠的方法。您也许可以查看user-agent字符串,但这可能会被欺骗或省略。或者,您也可以使用GeoIP服务来查找客户机的IP地址,但同样,这可以很容易地避免。

其他回答

你也可以使用第三方api通过用户代理字符串进行设备检测。其中一个这样的服务是www.useragentinfo.co。只需注册并获得你的api令牌,以下是你如何通过PHP获得设备信息:

<?php
$useragent = $_SERVER['HTTP_USER_AGENT'];
// get api token at https://www.useragentinfo.co/
$token = "<api-token>";
$url = "https://www.useragentinfo.co/api/v1/device/";

$data = array('useragent' => $useragent);

$headers = array();
$headers[] = "Content-type: application/json";
$headers[] = "Authorization: Token " . $token;

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($status != 200 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);

echo $json_response;
?>

如果访问者使用的是iPhone,下面是示例回复:

{
  "device_type":"SmartPhone",
  "browser_version":"5.1",
  "os":"iOS",
  "os_version":"5.1",
  "device_brand":"Apple",
  "bot":false,
  "browser":"Mobile Safari",
  "device_model":"iPhone"
}

我发现移动检测非常简单,你可以使用isMobile()函数:)

这个简单的解决方案

if(
    
    strpos($_SERVER['HTTP_USER_AGENT'],'Phone')
    |
    strpos($_SERVER['HTTP_USER_AGENT'],'Android')
    
    
){      echo "should be mobile";                }
else{   echo "give them the desktop version";   }

适用于我测试的大多数设备(通过浏览器开发工具设备模拟)。

当然,你可以简单地使用echo($_SERVER['HTTP_USER_AGENT'])查看自己使用的值。

在我的情况下,唯一丢失的智能手机设备是黑莓z30,我通过检查“触摸”来修复它。对于诺基亚N9,我也检查了“诺基亚”。显然,如果发现“未检查”,可以将这些添加到更多设备上。但现在,这可能比上面一些更复杂的字符串扫描模式更好/更快地理解。

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

您只需要包含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;
}
?>