codeigniter check for user session in every controller

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?


Solution 1:

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

Solution 2:

Put it in a helper and autoload it.

helpers/login_helper.php:

function is_logged_in() {
    // Get current CodeIgniter instance
    $CI =& get_instance();
    // We need to use $CI->session instead of $this->session
    $user = $CI->session->userdata('user_data');
    if (!isset($user)) { return false; } else { return true; }
}

config/autoload.php:

$autoload['helper'] = array('login');

Then in your controller you can call:

is_logged_in();

Solution 3:

You can achieve this using helper and CodeIgniter constructor.

  1. You can create custom helper my_helper.php in that write your function

    function is_logged_in() {
      $user = $this->session->userdata('user_data');
      if (!isset($user)) { 
       return false; 
      } 
     else { 
       return true;
     }
    } 
    
  2. In controller if its login.php

    class Login extends CI_Controller {
    
        public function __construct()
        {
            parent::__construct();
            if(!is_logged_in())  // if you add in constructor no need write each function in above controller. 
            {
             //redirect you login view
            }
        }
    

Solution 4:

I think using hooks is pretty easy. Just create a hook to check $this->session->user. It will be called in every request.

Solution 5:

Get all user's data from session.

In the Controller,

$userData = $this->session->all_userdata();

In the View,

print_r($userData);