通过PHP获取当前是手机端还是平板端

本文介绍了一个使用PHP编写的函数,该函数可以根据用户代理字符串来判断访问设备是手机、平板还是桌面电脑。通过搜索特定的关键词如'iPhone'、'Android'、'Windows Phone'等来区分不同的设备类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本人小菜鸟一枚,刚加入博客平台大笑,借鉴大神的写法,记录一下

/**
 * PHP 判断设备是否是手机还是平板的方法
 * @staticvar bool $is_mobile
 * @return bool
 */

function userAgent($ua){

    $iphone = strstr(strtolower($ua), 'mobile'); //Search for ‘mobile‘ in user-agent (iPhone have that)
    $android = strstr(strtolower($ua), 'android'); //Search for ‘android‘ in user-agent
    $windowsPhone = strstr(strtolower($ua), 'phone'); //Search for ‘phone‘ in user-agent (Windows Phone uses that)

    $androidTablet = androidTablet($ua); //Do androidTablet function
    $ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent

    if($androidTablet || $ipad){ //If it‘s a tablet (iPad / Android)
        return 'tablet';
    }
    elseif($iphone && !$ipad || $android && !$androidTablet || $windowsPhone){ //If it‘s a phone and NOT a tablet
        return 'mobile';
    }
    else{ //If it‘s not a mobile device
        return 'desktop';
    }
}

function androidTablet($ua){ //Find out if it is a tablet
    if(strstr(strtolower($ua), 'android') ){//Search for android in user-agent
        if(!strstr(strtolower($ua), 'mobile')){ //If there is no ‘‘mobile‘ in user-agent (Android have that on their phones, but not tablets)
            return true;
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值