i3jfma
Last Updated: February 25, 2016
·
6.239K
· rayfranco

Session control in CodeIgniter (the flexible way)

<?php

class Backend_Controller extends Controller {

    var $data = array();

    function Backend_Controller() {

        parent::Controller();

        // Session control
        // Example of how I give (the simple way) a user the credentials
        // I set this after a login process controlled by MY_Controller
        $session_data = array(
            'id' => 1,
            'username' => 'johndoe',
            'credentials' => 80, // Credentials between 0 and 100 in my case
            'email' => 'john@doe.com',
        );
        $this->session->set_userdata('user',$session_data);
        // End of credentials assignment

        if (!$this->session->userdata('user')) {
            redirect('actions/login');
        }


        $this->user = $this->session->userdata('user');

        // Uncomment to set a minimum credentials level needed to access the whole backend
        // $this->session_control(50);
    }

    function session_control($min_credentials = 100, $redirect = TRUE) {

        if (!isset($this->user['credentials']) OR $this->user['credentials'] < $min_credentials) {
            if ($redirect === TRUE) {
                redirect('actions/login');
            } else {
                return FALSE;
            }
        } else {
            return TRUE;
        }
    }
}

?>

This is how I deal both a Backend and a Frontend in my CodeIgniter projects. The principle is to extends the main CI controller for the frontend, and then, have a specific Controller for the Backend, extending MY_Controller.

Then I extend all my backend controllers to my Backend_Controller, I also rename all my backend controller files like this :

backend_name_of_the_controller.php

After changing the routes (config/routes.php) like this :

$route['_admin'] = 'backend_dashboard/index'; // Default controller
$route['_admin/(:any)'] = "backend_$1/index"; // Default method
$route['_admin/(:any)/(:any)'] = "backend_$1/$2";

Then in all my controllers, I can verify the user credentials and load specific views this way :

<?php

require_once APPPATH.'libraries/Backend_Controller.php';

class Backend_dashboard_controller extends Backend_Controller {

    function Backend_dashboard_controller() {

        parent::Backend_Controller();
    }

    function index() {

        $this->session_control(50);

        if ($this->session_control(100, FALSE)) {
            $this->data['admin_panel'] = $this->load->view('slots/admin_panel',$this->data, TRUE);
        }
    }
}

?>

EDIT : Someone comes to me with an issue, be careful to set the login page under the control of MYContoller or CIController, but you'll go through an infinite loop if you set it under the BackendController (due to the redirection in the BackendController constructor).