Member Avatar for iamthwee

Evening ladies and gents. Just wondering what is common practice but once a session is set I have been using a validate session in each method/function in my controller.

Seems like a lot of typing... necessary ... still a lot of typing. Is this what everyone else does?

Ta.

You can check the session in the constructor method, for example:

class Test extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        # Check the session
        if($this->session->userdata('is_valid') !== TRUE)
        {
            # unset session
            ...

            # redirect out
            redirect('/logout');
        }
    }

    # other methods
    public function index()
    {
        return 'hello';
    }
}

In alternative you can move the check to another controller and then load it on each reserved controller. For example, in application/core/ create MY_Controller.php and paste:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        if($this->session->userdata('is_valid') !== TRUE)
        {
            # unset session
            # redirect out
        }
    }
}

Then in your reserved controller (in this example Test) change this line:

class Test extends CI_Controller

to:

class Test extends MY_Controller

So, each time you open a method of the Test controller, the parent constructor is loaded and the check is performed. Basically you could overwrite only the core controller, but by applying __autoload() to the application/config/config.php as explained in the second link, you can create all the extension you need: MY_Account, MY_Admin, MY_Anonymous and so on...

Docs:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.