尝试在codeigniter中创建登录会话挂钩

时间:2016-12-15 11:52:01

标签: php codeigniter

我在hook.php中有这个:

$hook['post_controller_constructor'][] = array(
    'class'    => 'Account',
    'function' => 'check_user_login',
    'filename' => 'authenticate.php',
    'filepath' => 'hooks/authenticate',
    'params'   => array()
    );

这是在hooks文件夹authenticate.php:

<?php
class Account
{
    function check_user_login()
    {
        if($this->session->userdata('is_logged_in')){
            redirect('pag/index');    
        }else{
            redirect('main/restricted');
        }
    }
}
?>

我想让登录会话可用于所有模型/控制器,但有些事情是不对的,我也设置了$ config ['enable_hooks'] = TRUE;感谢

2 个答案:

答案 0 :(得分:1)

试试这个(hooks.php

$hook['post_controller_constructor'][] = array(
                               'class'    => 'Authenticate',
                               'function' => 'check_user_login',
                               'filename' => 'Authenticate.php',
                               'filepath' => 'hooks',
                               'params'   => array()
                               );

现在在Authenticate.php文件夹

中挂钩文件(hooks
<?php
class Authenticate{
  protected $CI;

  public function __construct() {
    $this->CI = & get_instance();
  }
  public function check_user_login(){
      if(!$this->CI->session->is_logged_in){
          redirect('main/restricted');    
      }
  }
}
?>

您需要使用$this->CI =& get_instance()引用CI超级对象,然后通过调用$this->CI..

来获取最终数据

https://www.codeigniter.com/user_guide/general/hooks.html

  

如果您使用的是CodeIgniter版本3,则可以使用   而是$this->CI->session->is_logged_in   $this->CI->session->userdata('is_logged_in')

答案 1 :(得分:0)

您是否使$ config ['enable_hooks'] = TRUE;从应用程序文件夹下的config文件夹中的config.php文件中获取?