codeigniter check for user session in every controller

user393964 picture user393964 · Sep 9, 2010 · Viewed 65.1k times · Source

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->userdata('user_data');

   if (!isset($user)) { 
      return false; 
   } 
   else { 
      return true;
   }

}

Problem is that I have more than one Controller. How can I use this function in those other controllers? Redefining the function in every Controller isn't very 'DRY'.

Any ideas?

Answer

Stephen Curran picture Stephen Curran · Sep 10, 2010

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