views:

260

answers:

1

Hi

I have some CodeIgniter controllers which should only be accessed by users who have logged in (i.e. where $this->session->userdata('username') is not null). If a non-authenticated person attempts to access said controllers they should receive:

header('location: /auth/login');

There has got to be a better way to do this than to put a

if (!$this->session->userdata('username'))
    header('location: /auth/login');
else
{
    [rest of function]
}

in front of every function in the controller...

I know DX_Auth has a similar functionality, but I am not using an authentication plugin and I am not open to doing so.

Thanks!
Mala

+4  A: 

Do the user login check when the class is created, so it doesn't matter what function the user is accessing it will check for the session variable and redirect to the login page on failure:

function className()
{
    parent::Controller();
    if(!$this->session->userdata('username')) header('location: /auth/login');
}

That's the way of calling the __constructor or it's equivalent in codeigniter when you create controllers/models, or at least that's what I understood!

johnnyArt
Ah cheers mate :) I hadn't thought of instantiating these things!
Mala
Does it work? Can't try it here :P
johnnyArt
Yes it works a charm, thanks so much! For controllers where only specific functions are "restricted" is there a way of putting that in the constructor as well? Or for those do I need to just stick a if/header block in front of the functions?
Mala