filter:
使用CI的hooks来实现filter.
1.在system/application/config/config.php中,把enable_hooks的值改为TRUE
$config['enable_hooks'] = TRUE;
2.在syste/application/config/hooks.php中,添加hooks,如下
$hook['post_controller_constructor'] = array(
'class' => 'SecurityFilterChain',
'function' => 'do_filter',
'filename' => 'security_filter_chain.php',
'filepath' => 'hooks',
'params' => array(
'logged_in_session_attr' => 'logged_in',
'login_page' => '/login/',
'should_not_filter' => array('/^//login$/', '/^//login//.*$/', '/^//user//profile.*$/'),
'need_admin_role' => array('/^//user$/', '/^//user//.*$/', '/^//role$/', '/^//role//.*$/')
)
);
其中params 是传递给filter类的参数.
shoud_not_filter是不需要过滤的uri
need_admin_role是需要管理员角色的uri
3.生成文件system/application/hooks/security_filter_chain.php
class SecurityFilterChain {
function do_filter($params)
{
$CI = &get_instance();
$uri = uri_string();
foreach($params['should_not_filter'] as $not_filter)
{
if(preg_match($not_filter, $uri) == 1)
{
return;
}
}
if(!$CI->session->userdata($params['logged_in_session_attr']))
{
redirect($params['login_page']);
}
foreach($params['need_admin_role'] as $need_admin)
{
if(preg_match($need_admin, $uri) == 1)
{
$current_user = $CI->session->userdata('current_user');
if(!isset($current_user['role_status']) or $current_user['role_status'] != 0) // 0表示管理员角色的id
{
show_error('您没有权限访问这个页面', 403);
return;
}
break;
}
}
}
}
helper
添加自定义的helper,名称为test
1.创建文件system/application/helpers/test_helper.php内容为:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('array_to_option'))
{
function array_to_option($name, $data = array())
{
$html = "<select name=/"$name/">";
foreach($data as $value => $text)
{
$html .= "<option value=/"$value/">$text</option>";
}
$html .= "</select>";
return $html;
}
}
2.加载这个helper
在autoload.php里边,autoload['helper']中添加test
$autoload['helper'] = array('url', 'form', 'test');
或者在controller的构造函数中添加
$this->load->helper('test')
3.使用。直接调用函数array_to_option即可