Thinkphp5所有頁面驗證用戶是否登陸


新建Base.php控制器,所有的頁面繼承自它

<?php
namespace app\index\controller;
use think\Controller;

class Base extends Controller
{
    public function __construct(){
        /**
         * 不驗證用戶登陸的頁面
         */

        //不驗證用戶登陸的頁面
        $exception_arth_list=[
            'member/users/login', //登陸頁面
            'member/users/reg'    //注冊頁面
        ];
        $redirect_url='member/users/login';
        $this->checkUserLogin($redirect_url,$exception_arth_list);
    }

   
    /**
    *  檢查用戶是否登陸,登陸時跳轉到登陸頁面
    *  $redirect_url 要跳的url (不區別大小寫) [str] 例: 'member/Users/login'
    *  $exception_arth_list [array] 不驗證用戶登陸的頁面地址(不區別大小寫) 例:     ['member/user/login','member/Users/reg']
    *  $msg 跳轉前的提示信息
    */
    protected function checkUserLogin($redirect_url,$exception_arth_list=[],$msg='')
    {
        if(!is_string($redirect_url) || !is_array($exception_arth_list) || !is_string($msg) ){
            die('傳入的參數錯誤.');
        }
      
        //獲取到當前訪問的頁面
        $module=request()->module();//獲取當前訪問的模塊
        $controller=request()->controller();//獲取當前訪問的控制器
        $action= request()->action();//獲取當前訪問的方法
        $current_auth_str=$module.'/'.$controller.'/'.$action; //轉成字符串
       
        //不驗證用戶登陸的頁面
        //把數組里的全部轉小寫
        if(!empty($exception_arth_list) && is_array($exception_arth_list)){
            foreach($exception_arth_list as &$v){
                if(!is_string($v)){
                    die('不驗證頁面數組里的值只能為字符串類型.');
                }
                $v=strtolower($v);
            }
        }
        //當前訪問的頁面$current_auth_str轉為全小寫后,如果不在$exception_arth_list客戶中就驗證用戶是否登陸
        if(!empty($exception_arth_list) && is_array($exception_arth_list)){
            if(!in_array(strtolower($current_auth_str),$exception_arth_list)){
                if (!session('user_id')) {
                    if($msg == ''){
                        $this->redirect($redirect_url);
                    }else{
                        $this->error('請先登陸.', $redirect_url);

                    }
                }
            }
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM