简体   繁体   English

用PHP检测移动设备

[英]Detect mobile device in PHP

I have a slider, it shows 4 videos, I need to show the picture when I go through with mobile device, video when through a desktop , the slider is written in main.min.js , and includeed in the main.tpl (template), and i have a script that detect mobile device 我有一个滑块,它显示4个视频,我需要在浏览移动设备时显示图片,视频通过桌面时,滑块写在main.min.js ,并包含在main.tpl (模板中) ),我有一个检测移动设备的脚本

require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {

}

// Any tablet device.
if( $detect->isTablet() ){

what should i do to show the picture when I go through with mobile device, video when through a desktop? 当我通过移动设备,通过桌面进行视频时,我该怎么做才能显示图片?

I think the best way is to check by user agent. 我认为最好的方法是通过用户代理进行检查。 WordPress has a wp_is_mobile fucntion in it's core that might help (I've removed WP parts of it): WordPress在它的核心中有一个wp_is_mobile功能可能会有所帮助(我删除了它的WP部分):

function is_mobile() {
    if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
        $is_mobile = false;
    } elseif ( strpos( $_SERVER['HTTP_USER_AGENT'], 'Mobile' ) !== false // many mobile devices (all iPhone, iPad, etc.)
        || strpos( $_SERVER['HTTP_USER_AGENT'], 'Android' ) !== false
        || strpos( $_SERVER['HTTP_USER_AGENT'], 'Silk/' ) !== false
        || strpos( $_SERVER['HTTP_USER_AGENT'], 'Kindle' ) !== false
        || strpos( $_SERVER['HTTP_USER_AGENT'], 'BlackBerry' ) !== false
        || strpos( $_SERVER['HTTP_USER_AGENT'], 'Opera Mini' ) !== false
        || strpos( $_SERVER['HTTP_USER_AGENT'], 'Opera Mobi' ) !== false ) {
            $is_mobile = true;
    } else {
        $is_mobile = false;
    }
    return $is_mobile;
}

For detecting if a mobile device is a tablet or a phone, I don't think user agent help much. 为了检测移动设备是平板电脑还是手机,我不认为用户代理有多大帮助。 here is a list of tablet user agents that I found: Tablet User Agents 这是我找到的平板电脑用户代理列表: 平板电脑用户代理

Try this class http://mobiledetect.net , it's best for detecting different devices. 试试这个类http://mobiledetect.net ,它最适合检测不同的设备。

// Include and instantiate the class.
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {
    // Show the image here for mobile
}

if ( !$detect->isMobile() ) {
    // Show the image here for computer
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM