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

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

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


当前回答

如果您的服务器支持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 
}
?>

其他回答

这个简单的解决方案

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,我也检查了“诺基亚”。显然,如果发现“未检查”,可以将这些添加到更多设备上。但现在,这可能比上面一些更复杂的字符串扫描模式更好/更快地理解。

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

//-- Very simple way
$useragent = $_SERVER['HTTP_USER_AGENT']; 
$iPod = stripos($useragent, "iPod"); 
$iPad = stripos($useragent, "iPad"); 
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android"); 
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices 

$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS);

if (!$DEVICE) { ?>

<!-- What you want for all non-mobile devices. Anything with all HTML, PHP, CSS, even full page codes-->

<?php }else{ ?> 

<!-- What you want for all mobile devices. Anything with all HTML, PHP, CSS, even full page codes --> 

<?php } ?>

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

也许结合一些javascript和PHP可以达到这个目的

<?php
$string = '<script>';
$string .= 'if ( /Opera|OPR\/|Puffin|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { ';
$string .= '        alert("CELL")';
$string .= '    } else {';
$string .= '        alert("NON CELL")';
$string .= '    }       ';  
$string .= '</script>'; 
echo $string;
?>

我也将其与纯javascript一起使用