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.
        }
    }
}
    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();
    You can achieve this using helper and CodeIgniter constructor.
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;
 }
} 
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
        }
    }
I think using hooks is pretty easy. Just create a hook to check $this->session->user. It will be called in every request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With