检测移动浏览器

2022-08-30 13:34:38

可能的重复:
检测移动设备的最简单方法

我有一个网站,我想检测使用的浏览器并重定向它们。我有一个php索引,代码必须用php。我发现了很多网站,但它们不起作用,或者它们没有检测到很多移动浏览器。您知道任何可以检测许多移动浏览器的好代码或教程吗?


答案 1

拥有我的用户代理代码:

<?php

/* USER-AGENTS
================================================== */
function check_user_agent ( $type = NULL ) {
        $user_agent = strtolower ( $_SERVER['HTTP_USER_AGENT'] );
        if ( $type == 'bot' ) {
                // matches popular bots
                if ( preg_match ( "/googlebot|adsbot|yahooseeker|yahoobot|msnbot|watchmouse|pingdom\.com|feedfetcher-google/", $user_agent ) ) {
                        return true;
                        // watchmouse|pingdom\.com are "uptime services"
                }
        } else if ( $type == 'browser' ) {
                // matches core browser types
                if ( preg_match ( "/mozilla\/|opera\//", $user_agent ) ) {
                        return true;
                }
        } else if ( $type == 'mobile' ) {
                // matches popular mobile devices that have small screens and/or touch inputs
                // mobile devices have regional trends; some of these will have varying popularity in Europe, Asia, and America
                // detailed demographics are unknown, and South America, the Pacific Islands, and Africa trends might not be represented, here
                if ( preg_match ( "/phone|iphone|itouch|ipod|symbian|android|htc_|htc-|palmos|blackberry|opera mini|iemobile|windows ce|nokia|fennec|hiptop|kindle|mot |mot-|webos\/|samsung|sonyericsson|^sie-|nintendo/", $user_agent ) ) {
                        // these are the most common
                        return true;
                } else if ( preg_match ( "/mobile|pda;|avantgo|eudoraweb|minimo|netfront|brew|teleca|lg;|lge |wap;| wap /", $user_agent ) ) {
                        // these are less common, and might not be worth checking
                        return true;
                }
        }
        return false;
}

?>

如何使用:

<?php
$ismobile = check_user_agent('mobile');
if($ismobile) {
return 'yes';
} else {
return 'no';
}
?>

答案 2

我编写此脚本是为了检测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/");

如果您有任何疑问,请告诉我,祝您好运!


推荐