Codeigniter Hooks advance

2019-07-21 21:17发布

问题:

Hello i am using post_controller hooks to validate user whether logged in or not But when validation fails i redirect user to login controller.... Now the problem is when it redirect to defaults controller post_controller hooks is called again and in this way infinite loop starts with redirection repeatedly. i want to call post_controller hook for every controller except login controller.... also is there way that i don't need to load session library again and again because, if user is logged in then it loads session library in post controller as well as via auto-load in config file... Here is my code


    //Hooks
    $hook['post_controller'] = array(
                                'class'    => 'is_login',
                                'function' => 'index',
                                'filename' => 'is_login.php',
                                'filepath' => 'hooks'
                                ); 

//Is_Login Hook class is_login { function __construct(){ $this->CI =& get_instance(); if(!isset($this->CI->session)) //Check if session lib is loaded or not $this->CI->load->library('session'); //If not loaded, then load it here } public function index() { $login_id = $this->CI->session->userdata('login_id'); $login_flag = $this->CI->session->userdata('logged_in'); if ($login_flag != TRUE || $login_id == "") { redirect(site_url().'/welcome_login', 'refresh'); } } }

回答1:

It seems it is not a good place to use Codeigniter hooks. It is better if you extend the Controller class in your application and in the constructor you can check if user is logged in and redirect to login controller. But no need to extend the login controller from your controller instead extend it from CI_Controller.



回答2:

I validate logins by hooks without problem. I just generate the login view when logged out and exit the application so that the only thing showing is the login, and the controller (and rest) gets ignored.

There's no need for redirect, really.



回答3:

if ($this->CI->uri->segment(1) != 'auth') {

    //Authenticate
    if (empty($user->user_id))redirect('auth');

}