Codeigniter Login check issue in construct / infinite loop

你说的曾经没有我的故事 提交于 2019-12-13 04:08:07

问题


i need to check is user loged or not.

i have to many function in controller, so i check it in construct function. but its entering infinite loop.

problem is: infinite loop.

  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'));
    }

}

i dont want to use $this->is_logged_in() in all functions/pages.


回答1:


The ugly hack would be:

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

I'm sure there are better ways, and the segment parts might be off, look up http://ellislab.com/codeigniter/user-guide/libraries/uri.html for more information.




回答2:


@Allan

It should be

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

Check the if condition.




回答3:


You might want to create a core controller then do the checking there if you don't want to use it on all your functions or pages on 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'));
        }
    }
}

then extend it like: On all your controllers that you want to verify login, or you can put the $this->_is_logged_in() function directly at your MY_Controller forcing all controllers that extends it to be checked. It's Up to you

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();
    }
}

I used protected so that only classes that extends my_controller can use it, and add un underscore at the name, so it can't be accessed via url



来源:https://stackoverflow.com/questions/16794141/codeigniter-login-check-issue-in-construct-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!