Using CodeIgniter I'm checking if a cookie exists by using the isset() function and depending on that I redirect to an other controller. Now my problem is that I get a redirect-loop because the check_logged_in function thinks that the cookie doesn't exists.
Here is my code:
This function resides in the login_helper
.
function check_logged_in()
{
if(!isset($_COOKIE['uid']))
{
redirect('users/login');
return FALSE;
}
else
{
return TRUE;
}
this next function resides in the home
controller and calls the check_logged_in() function, described above.
public function index()
{
$this->load->helper('url');
$this->load->helper('login');
$logged_in = check_logged_in();
if($logged_in === TRUE)
{
$this->load->view('templates/header');
$this->load->view('pages/home_view');
$this->load->view('pages/advanced_search_view');
$this->load->view('pages/contact_information_view');
$this->load->view('templates/footer');
}
}
the next function resides in the users
controller
public function login()
{
if(isset($_COOKIE['uid']))
{
redirect(home);
}
else
{
-some unrelated code-
}
when the cookie does exist and I run either the home/index
function or the users/login
function I end up in a redirect loop. When the cookie doesn't exist I end up at my login page, so it seems the users/login
cookie check works correctly but the home/index
function does not.
I have tried putting
if(!isset($_COOKIE['uid']))
{
redirect('users/login');
}
directly in the home/index
function but it gave the same problems.
Put the login check in the Constructor. Give it a generic name - and have it do something useful like return info from the cookie, and/or from a database lookup.
function __construct() {
parent::__construct();
// load the model
$this->load->model( 'login_model' );
// if logged in, return $this->user
if(! $this->user = $this->login_model->verifyUser() )
{ redirect('users/login', 'refresh'); }
} // construct
And now $this->user is available for your methods, all the way to the view.
If you need an "admin" that can do more then a user, in the same way
$this->admin = $this->login_model->verifyAdmin() ;
Then you can change what happens in verifyAdmin(), and your class does not have to get updated.