Reputation: 767
I have created a simple login in codeigniter, where user enter his/her username and password and if valid then go to some protected page. Protected page has a link called logout. But the problem is after logout if i directly access to protected page it does not redirect to login page.
my protected page contain
<?php
if (!isset($this->session->userdata['loggedin'])) {
redirect("login");
}
?>
Welcome Dear!!
<a href="login/logout">Logout</a>
I have set the session data after successful user credential.
//set the session variables
$sessiondata = array(
'username' => $username,
'loggedin' => TRUE
);
$this->session->set_userdata($sessiondata);
redirect('admin');
In logout method (login is my controller) I have unset the session data like this-
// Removing session data
$sess_array = array(
'username' => '',
'loggedin' => FALSE
);
$this->session->unset_userdata($sess_array);
But after logout when I access directly to admin page(protected) it does not redirect to login page.
After logout I debugged with this on login page, and it shows the already stored session value.
echo $this->session->userdata['username'];
but when i use on logout method it works fine.
$this->session->sess_destroy();
Can anyone tell me why this is happended? Does unset_userdata not working properly or I have done something wrong? Thanks in advanced.
Upvotes: 0
Views: 1405
Reputation: 328
Above answer Ashis Biswas is fine and you also need to take care that you should check your login session in your controller as in codeigniter you are accessing your controller function instead of view. if you will check and redirect on view page that will not redirect to your login controller even if you have unset session data.
Upvotes: -1
Reputation: 1549
There issue in handling the session in codeigniter functionality:
$sess_array = $this->session->all_userdata();
foreach ($sess_array as $key => $val) {
if ($key != 'session_id' && $key != 'last_activity' && $key != 'ip_address' && $key != 'user_agent')
$this->session->unset_userdata($key);
}
Upvotes: 1
Reputation: 767
Ok i solve this problem. The problem is codeigniter does not accept array of pairs when unset session data. i.e
I used this code on my application-
// Removing session data
$sess_array = array(
'username' => '',
'loggedin' => FALSE
);
$this->session->unset_userdata($sess_array);
But codeigniter does not support this now. I altered this code with this below code
// Removing session data
$sess_array = array('username','loggedin');
$this->session->unset_userdata($sess_array);
Now it works fine.
Ref- https://www.codeigniter.com/user_guide/libraries/sessions.html
**In previous versions, the unset_userdata() method used to accept an associative array of key => 'dummy value' pairs. This is no longer supported.**
Upvotes: 1