Home >Backend Development >PHP Tutorial >PHP uses CI to implement URL permission control using hooks_PHP tutorial
CI's hook function allows you to change or increase the core running functions of the system without modifying the core system files.
For example, you can run a specific script just before or just after the controller loads, or trigger your script at other times.
Look at the code:
Add hook statement in system/application/config/hooks.php:
[php]
$hook['post_controller_constructor'] = array(
'class' => 'Acl',
'function' => 'filter',
'filename' => 'acl.php',
'filepath' => 'hooks',
);
Make the hook system take effect in system/application/config/config.php
$config['enable_hooks'] = TRUE;
Then create a new acl.php permission system configuration file in , of course you can also put it in the database.
//Visitor permission mapping
$config['acl']['visitor'] = array(
'' => array('index'),//Homepage www.2cto.com
'music' => array('index', 'list'),
'user' => array('index', 'login', 'register')
);
//Administrator
$config['acl']['admin'] = array(
);
//-------------Configure prompt information and jump url for insufficient permissions------------------//
$config['acl_info']['visitor'] = array(
'info' => 'Login required to continue',
'return_url' => 'user/login'
);
$config['acl_info']['more_role'] = array(
'info' => 'Requires higher privileges to continue',
'return_url' => 'user/up'
);
/* End of file acl.php */
/* Location: ./application/config/acl.php */
Add acl.php logical processing file in the system/application/hooks directory
class Acl
{
Private $url_model;//Module accessed, such as: music
Private $url_method;//The accessed method, such as: create
Private $url_param;//The parameter in the url may be 1 or id=1&name=test
private $CI;
Function Acl()
{
$this->CI = & get_instance();
$this->CI->load->library('session');
$url = $_SERVER['PHP_SELF'];
$arr = explode('/', $url);
$arr = array_slice($arr, array_search('index.php', $arr) + 1, count($arr));
$this->url_model = isset($arr[0]) ? $arr[0] : '';
$this->url_method = isset($arr[1]) ? $arr[1] : 'index';
$this->url_param = isset($arr[2]) ? $arr[2] : '';
}
function filter()
{
$user = $this->CI->session->userdata('user');
if (emptyempty($user)) {//游客visitor
$role_name = 'visitor';
} else {
$role_name = $user->role;
}
$this->CI->load->config('acl');
$acl = $this->CI->config->item('acl');
$role = $acl[$role_name];
$acl_info = $this->CI->config->item('acl_info');
if (array_key_exists($this->url_model, $role) && in_array($this->url_method, $role[$this->url_model])) {
;
} else {//无权限,给出提示,跳转url
$this->CI->session->set_flashdata('info', $acl_info[$role_name]['info']);
redirect($acl_info[$role_name]['return_url']);
}
}
}
摘自 I am heweilun