CI的面向切面的普通權限驗證

第一步:開啓CI的鉤子配置,這次很少說看CI手冊便可。php

第二步:在cofig/hooks.php中進行鉤子配置,CI手冊中有記載html

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*$hook['post_controller_constructor'][] = array(
    'class'    => 'Jurisdiction',
    'function' => 'prevent',
    'filename' =>'Jurisdiction.php',
    'filepath' => 'hooks'
);*/

第三步:編寫鉤子邏輯,總的思路就是在加載配置文件中的不須要驗證的頁面控制器名稱,例如login,而後進行判斷是否在數組中若是在數組中即爲不進行驗證,若是須要驗證就進行跳轉。hooks/  目錄下json

<?php
class Jurisdiction{
    private $url_model;//所訪問的模塊,如:music
    private $url_method;//所訪問的方法,如:create
    private $url_param;//url所帶參數 多是 1 也多是 id=1&name=test
    private $CI;

    function __construct(){
        $this->CI = & get_instance();
        $this->CI->load->library('session');
        $this->CI->load->helper('url');
        $this->CI->load->config('jurisdiction');
        if (!session_id()) session_start();
        $url = $_SERVER['PHP_SELF'];
        $arr = explode('/', $url);
        $this->url_model =  $arr[2];
    }
    function prevent(){
        $non_verification = $this->CI->config->item('non_verification');
        if(!in_array($this->url_model,$non_verification)){
            if(empty($this->CI->session->username)){
                echo json_encode(['state'=>'fail','url'=>'http://10.32.186.11/login.html']);
                die();
            }
        }
    }
}
?>

加載的配置文件數組

<?php
$config['non_verification'] = [
    'Login'
];
?>
相關文章
相關標籤/搜索