codeigniter check for user session in every controller

前端 未结 7 1573
再見小時候
再見小時候 2020-11-30 23:54

I have this private session in one of my controllers that checks if a user is logged in:

function _is_logged_in() {

   $user = $this->session->userdat         


        
7条回答
  •  孤独总比滥情好
    2020-12-01 00:41

    Another option is to create a base controller. Place the function in the base controller and then inherit from this.

    To achieve this in CodeIgniter, create a file called MY_Controller.php in the libraries folder of your application.

    class MY_Controller extends Controller
    {
        public function __construct()
        {
            parent::__construct();
        }
    
        public function is_logged_in()
        {
            $user = $this->session->userdata('user_data');
            return isset($user);
        }
    }
    

    Then make your controller inherit from this base controller.

    class X extends MY_Controller
    {
        public function __construct()
        {
            parent::__construct();
        }
    
        public function do_something()
        {
            if ($this->is_logged_in())
            {
                // User is logged in.  Do something.
            }
        }
    }
    

提交回复
热议问题