codeigniter check for user session in every controller

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.
        }
    }
}

Leave a Comment