thinkphp判断是否登录

自己写一个BasicController继承了官方的Controller,将判断登录的代码放在BasicController中,然后让其他自己编写的Controller都继承BasicController。

这里使用了_initialize()方法。

class BasicController extends Controller
{
    public function _initialize(){
    //获取登录的cookie,正常则返回uid,没有或异常则返回false,具体略
    $uid = getUidByCookie();
        //如果未登录,或cookie有异常
        if (!$uid) {
            $actionName = strtolower(ACTION_NAME);
            $controllerName = strtolower(CONTROLLER_NAME);
            switch ($controllerName) {
                case "task":
                    //task控制器中的show、search、worker操作方法不需要登录
                    if (!in_array($actionName, array("show", 'search', 'worker'))) {
                        $this->error('需要登录', U('User/login'), 1);
                        exit;
                    }
                    break;
                case "user":
                    //user控制器中的login、logout操作方法不需要登录
                    if (!in_array($actionName, array('login', 'logout'))) {
                        $this->error('需要登录', U('User/login'), 1);
                        exit;
                    }
                    break;
            }
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/shenxinpeter/p/6211496.html