简体   繁体   中英

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

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):

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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