Thinkphp5判断是否使用手机访问,TP5如何区分PC端还是手机端访问?

发布时间 2023-11-06 16:07:38作者: 圆柱模板
判断用户是否使用手机端访问,这个是我们做web研发时经常遇到的一个功能点。

一个很简单的功能点,解决方案也有很多种,比如使用原生PHP通过分析UA来判断。

但如果你的后端用的是ThinkPHP5框架的话,解决这个功能点就更简单了,因为TP5的源码中已经封装好了,我们可以直接使用。

 

1
2
3
4
5
6
7
8
//手机端首页的controller层代码
public function index() {
    if(request()->isMobile()){//如果是手机端访问重定向到手机端路径
        $this->redirect('wap/index/index');
    else {
        include template('index');
    }
}

 

1
2
3
4
5
6
7
8
//PC端首页的controller层代码
public function index() {
    if(!request()->isMobile()){//如果是PC端访问重定向到PC端路径
        $this->redirect('index/index/index');
    else {
        include template('index');
    }
}

 

上面的举例代码就是使用了TP5封装好的方法,这个方法的源码在request文件中,方法名称isMobile(),原理同样是通过分析用户的UA来判断访问来源。

醉学网-探索知识,成就未来! (nongpin88.com)