Reputation: 4609
I am utilizing a custom MY_Controller to authenticate users on my Codeigniter website.
I utilize $this->load->vars($data);
such that I can access the users information in views.
My first question is, does $this->load->vars($data);
allow access in models, and if so how - i couldn't find any information. If not, how can I get my logged in users username to my models without having to pass it through a controller every time?
Secondly... if the user is not logged in, I redirect them redirect(base_url() . 'account/login');
This works great, except because my account controller also extends MY_Controller, it gets stuck in an infinite redirect loop. I can just not extend the custom controller for this page, but I see no reason why a logged in user should not still be able to look at the login page.. any ideas?
Finally.. if a user is logged in, $user['username']
is defined in my views.
If a user is not logged in, it is not defined.
As such if i have if($user['username']!=''){
within my code, when a user IS logged in, all is fine and the code executes, however when no user is logged in errors pop up as regards an undefined variable being used in an if statement...
Codeigniter being difficult..
What is the work around here?
Many Thanks !!
Upvotes: 1
Views: 1236
Reputation: 7902
I agree with Chris about storing user details in the session.
To check if a user is logged in you could write a gatekeeper function and place it in the controllers construct to protect controllers (and therefore the views). Something like;
function gatekeeper()
{
if (!isset($this->session->item('username')) || !$this->session->item('username'))
{
redirect('/account/login);
}
}
Upvotes: 1
Reputation: 8257
I would consider storing the userdata for the currently logged in user in the session so that you don't need to query it and pass it to the view every time. You can access session data in the controllers, views and models with $this->session->userdata('your_userdata_var_name');
.
The reason $user['username']
displays an error is probably because it's being completely removed, not set to an empty string (''
), in which case you are trying to access an undefined array key.
Upvotes: 1