2

我正在尝试在 CodeIgniter 中设置一个“post_controller_constructor”挂钩。目的是检查用户是否未登录,然后将他重定向回登录页面。

这是我的钩子配置数组:

$hook['post_controller_constructor']  = array(
   'class'     => 'Checkpoint',
   'function'  => 'check_status',
   'filename'  => 'checkpoint.php',
   'filepath'  => 'controllers'
);

这是 Hook 事件的类

class Checkpoint {
var $CI;
function __construct(){
    $this->CI =& get_instance();
}
function check_status() {
    if($this->CI->router->class == 'Login'){
        return;
    } 
    if (!isset($this->CI->session)){
        $this->CI->load->library('session');
    } 
    if(!$this->CI->session->userdata('log_status')){
        //redirect(site_url('login'));
        echo "not logged in";
    }
    else{
        echo "logged in";
    }
}}

现在这里有问题:

  1. 当它收到来自“登录”控制器的请求时,它不会从 check_status() 函数中的第一个 if 语句返回,并在加载视图之前打印“未登录”。

  2. 如果未设置会话用户数据,当我尝试重定向时,它会在我的浏览器中显示错误“此网页具有重定向循环”。出于这个原因,我已经注释掉了重定向语句

我能做些什么来解决这些问题?

4

1 回答 1

3

As I described in my comment that your problem is when you enter your site the hook checks whether you are logged in or not, so if you are not then it will redirect you to your login page which will also trigger the hook once again which will cause an infinite redirecting process. Here's a possible solution: First, assign a user_data (once the user enters your site) in your session that represents that the user is already in your site like:

$this->session->set_userdata('is_in_login_page', TRUE);

then in your hook you can check it like:

if(!$this->CI->session->userdata('log_status') &&
 !$this->CI->session->userdata('is_in_login_page') ){
    redirect(site_url('login'));
    echo "not logged in";
}

so once the user is redirected, the 'is_in_login_page' value will be set to TRUE and the server will not redirect him anymore.

it might sound silly but I think it's a good solution in your case.

NOTE: the is_in_login_page should be set to FALSE when the user is not logged in and he is not on the login page so the server will redirect him to it.

于 2013-09-21T08:18:01.667 回答