2

It’s been a while since I don’t use CI and I’m with a starter doubt.

EDIT:

class MY_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if(!$this->session->userdata('usuario')) {
            $this->load->view('login');
        }
    }

}

class Home extends MY_Controller {

    public function __construct() {

        parent::__construct();
        Template::set('title', 'Login');
        Template::set('view', 'home');

    }

    public function index() {

        $this->load->view('template');

    }
}

What happens is that is the user session is invalid, it will load the login view but as in my Home controller contructor method is calling the view home, its loading both views on the same page.

1 Answer 1

1

Don't put this in a hook, put it in MY_Controller in the __construct() method.

http://codeigniter.com/user_guide/general/core_classes.html

Example:

// file application/core/MY_Controller.php
class MY_Controller extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        // your code here
    }

}

Just make sure that you extend MY_Controller instead of CI_Controller in the controllers you want to run this code in. If you have to change all of them, so be it.

UPDATE: You could also try a post_controller_constructor

post_controller_constructor

Called immediately after your controller is instantiated, but prior to any method calls happening.

But I would still prefer the MY_Controller method, as it is more flexible.

Sign up to request clarification or add additional context in comments.

6 Comments

The problem is that User_Controller extends MY_Controller, so it will be on a infinite loop
Then put it in the constructor of User_Controller. EDIT: How would that cause an infinite loop? It should work fine.
Just to be clear, you want every request to force a login except the actual login page, or do you want it only for certain controllers?
yes, check the session for each controller request, isn't that correct?
It depends on what you want to happen. BTW you need to exit when you load the login view, or preferably redirect to a login controller that doesn't extend the one where you do the session check.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.