第一步:开启CI的钩子配置,此次不多说看CI手册即可。
第二步:在cofig/hooks.php中进行钩子配置,CI手册中有记载
<?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/ 目录下
<?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'
];
?>