Search code examples
phpcodeignitercontrollers

Load a controller if authorized


I am trying to load a controller (Dashboard) if session is ok.

    if ($this->form_validation->run() == FALSE) {
     if(isset($this->session->userdata['logged_in'])){
    echo 'dashboard-01'; //test load
    $this->load->controllers('Dashboard');//Not sure if syntax is ok.

Is this possible? are there better approaches on how to do this?


Solution

  • What I usually do is to load the controller and check on its constructor if the user has enough credentials:

    class Sociedades extends CI_Controller {
    
        var $globales = array();
    
        function __construct()
        {
            parent::__construct();
            $this->load->database();
            $this->load->library(array('ion_auth','form_validation'));
            // Elliot, if you see this, don't delete it!
            $this->load->model('fSociety_model');
    
            if (!$this->ion_auth->logged_in())
            {
                //redirect them to the login page if not authorized
                redirect('auth/login', 'refresh');
            }
        }
    
        // then the index and other methods...
    }
    

    By the way, I'm using Ben Edmund's IonAuth.