Php – CodeIgniter customer Controller class says session is undefined

authenticationcodeigniterPHP

I'm using CodeIgniter (v1.7.2) and I've created a custom controller that incorporates authentication called MY_Controller (based on David Winter's blog post). When I load any controllers that use this base class, I get this error;

*Message: Undefined property: MY_Controller::$session*

Note that I am autoloading 'session' (and 'MY_controller' as a library) like so:

$autoload['libraries'] = array('database', 'session', 'MY_Controller');

Here is MY_Controller:

class MY_Controller extends Controller {
    public function __construct() {
        parent::__construct();      
        if (!$this->session->userdata('loggedin')) { <-- error is here
            header('Location: /sessions/login');
            exit();
        }
    }
}

Here's the controller that I'm trying to load:

class Welcome extends MY_Controller {

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

    function index() {
        $this->load->view('header');
        $this->load->view('welcome_message');
        $this->load->view('footer');
    }
}

When I var_dump $this->session above where the error occurs, I can see that it is NULL. Even putting $this->load->library('session'); in MY_Controller's constructor doesn't work. Why isn't it loading properly?

Thanks

Best Answer

Try taking MY_Controller out of the autoload.

$autoload['libraries'] = array('database', 'session');

You are extending the controller class which is automatically loaded by codeigniter as it is part of the core

Related Topic