I am fairly new and just started to use Codeigniter, and have come across some confusion regarding sessions.
What I want to achieve is, like in regular php, I want to check if a user is logged in by using a header include file which checks the session data. I dont want to check/write that checking code in every controller while passing data to the view file.
Can someone please show me how it can be done?
Ex. I don’t want to do the following in every controller:
//Controller:
if($this->session->userdata('loggedin'){
$data['loggedin'] = $this->session->userdata('loggedin');
}
//I dont want to check the above on every function in every controller
$this->load->view('some_view_file', $data);
//some_view_file
if(isset($loggedin)){
echo "You are logged in!";
}
else
{
echo "Please log in!";
}
Instead, I want something to like the following:
//some view file
if(isset($loggedin))
{
echo "your logged in";
}
else
{
echo "please log in";
}
And also, how can I use native php sessions instead of CI Sessions. Any help will be much appreciated. Thanks.
Firstly, theres no reason you can’t just write something like this in your view:
Then your controllers don’t need any of that code.
However if the check is more complex or something, then theres a few places you can do it.
1) In the constructor of a custom controller: create a new file
application/core/MY_Controller.php, and override the constructor with something like:then make all your controllers extend MY_Controller.
2) Or in a
post_controller_constructorhook. http://codeigniter.com/user_guide/general/hooks.html (this is more transparent, and probably easier if you have tons of controllers already)You can use native sessions with this:
http://codeigniter.com/wiki/Native_session/