codeigniter不活动会话注销

时间:2016-12-23 20:31:12

标签: codeigniter-3

我想知道当用户闲置几分钟时如何继续注销应用程序。我研究了一些事情,但没有找到任何可能有用的东西。

我正在使用codeigniter 3。

谢谢。

1 个答案:

答案 0 :(得分:1)

如果您想确保在一段时间不活动后,用户将被发送到登录页面,您可以使用ajax调用控制器中的logged函数来评估用户是否&# 39;会话仍然有效。

setInterval(function(){ 
    $.getJSON('url/to/controller/logged', function(response) {
        if (typeof response.redirect != 'undefined') {
            window.location.href = response.redirect;
         }
    });
}, <INTERVAL-IN-MILLISECONDS>);

要制作统一,您可以将原始CI_Controller类扩展到MY_Controller下名为application/core/MY_Controller.php的类,该类将用于扩展您的每个凭据保护控制器。 每次调用控制器中的任何函数时,将首先调用not_logged_in()函数。如果会话已过期,它将根据调用类型处理重定向。否则它会正常工作。

class MY_Controller extends CI_Controller{

    public function __construct(){
        parent::__construct();
        $this->not_logged_in();
    }

    private function not_logged_in(){
        $is_logged_in = $this->session->userdata('is_logged_in');

        // The cookie was not found or has expired
        if(!isset($is_logged_in) || $is_logged_in != true)
        {
            /* AJAX request check 
             * If it is not a AJAX request then redirects to login page
             */
            if( ! $this->input->is_ajax_request()) {
                redirect('login');
            } else{ // send and JSON message to redirect
                echo json_encode(array(
                    'status' => FALSE, 
                    'message' => 'Your session expired. Please, login.', 
                    'redirect' => base_url('login')
                ));
                exit();
            }
        }
    }

    public function logged()
    {
        // Request coming from AJAX call
        if($this->input->is_ajax_request()) {
            echo json_encode(array('status' => TRUE, 'message' => 'You are still logged in.'));
        } 
        else {
            show_404(); 
        }
    }

}

您在登录类中唯一需要更改的是在Cookie中添加is_logged_in字段。

class Login extends CI_Controller{

    // function called to validate credentials
    public function validate()
    {
        // ... code to validate login

        // If the user is validated
        $data = array(
            'is_logged_in' => true,
            ... // more user data, if you will
        ); 

        $this->session->set_userdata($data);
    }
}