Codeigniter在构造/无限循环中登录检查问题

时间:2013-05-28 14:02:50

标签: codeigniter login constructor codeigniter-2 login-control

我需要检查用户是否携带。

我必须在控制器中有很多功能,所以我在构造函数中检查它。但它进入无限循环。

问题是:无限循环。

  function __construct()
    {
        parent:: __construct();
        $this->is_logged_in();
        $this->clear_cache();
    }



 function is_logged_in()
{
            if( !class_exists('CI_Session') ) $this->load->library('session');

    if( $this->session->userdata('login') )
    {
        $data['name'] = $this->session->userdata('username');       

    }
    else
    {
        redirect(base_url('admin/login'));
    }

}

我不想在所有功能/页面中使用$this->is_logged_in()

3 个答案:

答案 0 :(得分:0)

丑陋的黑客将是:

function __construct()
{
    parent:: __construct();
    if (($this->uri->segment(2) == 'admin') && ($this->uri->segment(3) != 'login'))
        $this->is_logged_in();
    $this->clear_cache();
}  

我确信有更好的方法,并且细分部分可能已关闭,请查看http://ellislab.com/codeigniter/user-guide/libraries/uri.html以获取更多信息。

答案 1 :(得分:0)

@Allan

应该是

function __construct()
{
    parent:: __construct();
    if (!($this->uri->segment(2) == 'admin' && $this->uri->segment(3) == 'login'))
        $this->is_logged_in();
    $this->clear_cache();
} 

检查是否有条件。

答案 2 :(得分:0)

如果您不想在application/core

上的所有功能或页面上使用核心控制器,则可能需要创建核心控制器。
class MY_Controller Extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    protected function _is_logged_in()
    {
        if( !class_exists('CI_Session') ) $this->load->library('session');

        if( $this->session->userdata('login') )
        {
        $data['name'] = $this->session->userdata('username');       

        }
        else
        {


       if ($this->uri->segment(2) == 'admin' && $this->uri->segment(3) !== 'login')
        redirect(base_url('admin/login'));
        }
    }
}

然后将其扩展为:在您要验证登录的所有控制器上,或者您可以将其放入 $this->_is_logged_in()直接在MY_Controller函数强制检查扩展它的所有控制器。这取决于你

class admin Extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->_is_logged_in();
    }
}

class user Extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->_is_logged_in();
    }
}

我使用了protected,因此只有扩展my_controller的类才能使用它,并在名称中添加非下划线,因此无法通过url访问