codeigniter check for user session in every controller

Viewed 68674

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?

7 Answers

I coded like this according to above answers.. And this is running for me Create file my_helper.php

<?php 
    function _is_logged_in() {
        if(isset($_SESSION['username'])){
            return true;        
        } else {
            return false;
        }
    }
?>

Edit in autoload.php file

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

In your Controller file

class Welcome extends CI_Controller {

    public function __construct(){
        parent::__construct();

        if(!_is_logged_in())  
        {
            redirect("Login");
        }
    }
}
Related