Codeigniter destroy sessions separately - php

I use two different sessions for admin and user,and I want to destroy each session separately but when I destroy one session using $this->session->sess_destroy(); it destroys both sessions. Please help me.
$admin_data = array (
'admin_email' => $this->input->post('admin_email'),
'is_admin_logged_in' => 1
);
$this->session->set_userdata($admin_data);
redirect('admin_profile');
public function admin_profile() {
if ($this->session->userdata('is_admin_logged_in')){
$this->load->view("view_admin_profile");
}
else {redirect('login');}
}
public function logout() {
$this->session->unset_userdata($admin_data);
redirect("login");
}

you can use $this->session->unset_userdata('name of session');
for more info check the user-guide
https://www.codeigniter.com/user_guide/libraries/sessions.html

You can use :-
$this->session->unset_userdata('some_name');
unset_userdata() can be used to remove it, by passing the session key
For e.g :
If your admin session name is 'admin_id' and user session id is 'user_id' then you can seperately destroy both the session like this :-
$this->session->unset_userdata('admin_id'); // for admin
$this->session->unset_userdata('user_id'); // for user

To destroy the session in codeigniter simply do this;
function logout() {
$this->session->sess_destroy();
}

Related

Session is not being destroy in codeigniter

I am trying to unset my current logged in user's session.It's working fine if i am doing normal login but when i use remember me settings using cookies it's not being destroy.
My code for set the session and cookie is
public function login() {
if(isset($this->session->userdata['username']) || isset($_COOKIE['user_id'])){
$this->load->model('User');
$p_uid = $this->User->user_login($_COOKIE['user_id'], $_COOKIE['password']);
redirect(base_url() . "dashboard");
}else{
$this->form_validation->set_rules('user_id', 'User ID', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login/login');
} else {
$user_id = $this->input->post('user_id');
$password = $this->input->post('password');
$this->load->model('User');
$p_uid = $this->User->user_login($user_id, $password);
//var_dump($p_uid);
if ($p_uid) {
if(isset($_POST['remember_me'])){
setcookie("user_id",$user_id,time()+86400*30);
setcookie("password",$password,time()+86400*30);
}
redirect(base_url() . "dashboard/");
} else {
$data=array(
"error"=>"Wrong Userid Or Password"
);
$this->load->view('login/login',$data);
}
}
}
}
And My logout Function is:
public function logout(){
$this->load->helper('cookie');
delete_cookie("user_id");
delete_cookie("password");
$this->session->unset_userdata("username");
$this->session->sess_destroy();
redirect(base_url());
}
Where i am doing mistake. please help. Thanks
First of all, your remember-me mechanism is seriously flawed. See Implementing Secure User Authentication in PHP Applications with Long-Term Persistence.
I don't understand how your login works. You are checking if username is set in session, then are using cookies to perform login. I guess you've made it work as the first part of || always fails since $this->session->userdata['username'] will never be set. The correct way to access username from session would be:
$_SESSION['username']
OR
$this->session->userdata('username')
OR
$this->session->username
Finally, make sure the cookies are actually being deleted by inspecting your requests in network tab. Codeigniter deletes cookies by setting a negative expiration time of around a day, see if this is the case in your version of Codeigniter. For best results, just set the cookie again with large negative expiration time, and instead of checking if cookie is set, check if cookie is !empty.
I've faced the same issue a while ago. I was trying all methods which were possible. But I failed. Finally I found the solution with ob_start and ob_clean . Logout should be like this:
class controllerName extends CI_Controller
{
function __construct()
{
parent::__construct();
ob_start();
$this->load->library('Session');
$this->load->helper('cookie');
}
public function logout()
{
$this->load->driver('cache');
$user_id = array(
'name' => 'user_id',
'value' => '',
'expire' => '0',
'domain' => '.localhost',
'prefix' => ''
);
delete_cookie($user_id);
$this->session->sess_destroy();
$this->cache->clean();
ob_clean();
redirect(base_url());
}
}
To prevent browser back button previous page load, you should do something like this
$sess = $this->session->userdata('username');
if(empty($sess))
{
$this->session->set_flashdata('error', 'Session has Expired. Please login');
redirect('loginController/method');
}
else
{
# success.
# continue the normal code here
}
FYI: This should be added in every function or being used by a constructor to do it.
NOTE : Don't add password in cookie. Read - php cookie injection vulnerability?
To unset single element from session array:
$this->session->unset_userdata('some_name');
You can pass an array of keys to unset multiple values:
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
public function check_admin_login()
{
$admin_email_address=$this->input->post('admin_email_address',true);
$admin_password=$this->input->post('admin_password',true);
$this->load->model('admin_model','a_model');
$result= $this->a_model->check_admin_login_info($admin_email_address,$admin_password);
// echo '<pre>';
// print_r($result);
// exit();
$sdata=array();
if($result)
{
$sdata['full_name']=$result->admin_full_name;
$sdata['admin_id']=$result->admin_id;
$this->session->set_userdata($sdata);
//$sdata[]
redirect('super_admin');
}
else{
$sdata['message']='Your User Id / Password Invalide !';
$this->session->set_userdata($sdata);
$this->load->view('admin/admin_login');
}
}
for login and for logout
public function logout()
{
$this->session->unset_userdata('full_name');
$this->session->unset_userdata('admin_id');
$sdata=array();
$sdata['message']='You are Successfully Logout !';
$this->session->set_userdata($sdata);
redirect('admin');
}
This will happen when login page in http or localhost then codeigniter create session for http or locahost.
when we are trying get session in https://www.example.com or http://[::1]/ then the session will not added for these type of urls..
try to use one type of url pattern in website
For delete cookie
delete_cookie('name', $domain, $path);
For delete/destroy sesstion
$this->session->sess_destroy();
To destroy a particular session
$this->session->unset_userdata('name');
For multiple items
$items = array('item-name1' => '', 'item-name2' => '');
$this->session->unset_userdata($items);

cant get particular data from session in codeigniter

Controller:logic part
$query1['shipping']=$this->cart_model->get_shipping_info();
$query2['pay']=$this->cart_model->get_payment_info();
$query1=$this->session->set_userdata($query1);
$query2=$this->session->set_userdata($query2);
Model:fetch data from database
public function get_shipping_info()
{
$query=$this->db->query('select * from shipping;');
return $query->result();
}
public function get_payment_info()
{
$query=$this->db->query('select * from payment;');
return $query->result();
}
View:here goes the view that i want to show to user
print_r($this->session->userdata('shipping'));
echo "<br/>";
echo "<br/>";
print_r($this->session->userdata('pay'));
Depends if you auto-load the session library or not, we will need to include session library:
$this->load->library('session');
Then you able to get session :
$session_id = $this->session->userdata('SessionID');
And still can't get then try to store array instead of stdClass Object.
Does this get you what you need?
You are setting session like this 'shipping' and 'pay'. But in your session there is no variable created for this.
$newdata = array(
'shipping' => 'shipping_123',
'pay' => 'pay_456'
);
$this->session->set_userdata($newdata);
and to retrive the session you can use
echo($this->session->userdata('shipping')); # Outputs shipping_123
echo($this->session->userdata('pay')); # Outputs pay_456
While looking your code, I think you need to pass data from controller to view. If true mention it too
Read this
Session Library - Codeigniter.com

codeigniter kill session but use flashdata on redirect

I am trying to write a function to kill my users session if their status in the database (for either company or user) is changed to false (this works fine).
Unfortunately, codeigniter does not let you set_flashdata easily after killing the session. I cannot work out how to re-initialise a new session, in order to store the flashdata for the redirection to the login page (and tell the user why they were booted out).
Searching on here and google hasn't really afforded me anything on recreating a session to use. I use CodeIgniter 3.0.3
Helper code:
function user_active($username)
{
$CI =& get_instance();
$CI->load->database();
$CI->db->where('username', $username);
$CI->db->from('users');
$CI->db->join('company', 'company.orgID = users.orgID');
$query = $CI->db->get();
$result = $query->row_array();
// check company active
if($result['orgStatus'] != TRUE){
$CI->session->sess_destroy();
$CI->session->set_flashdata('flashError', 'Company currently disabled please contact accounts for reactivation');
redirect(site_url(), 'refresh');
}
// check user active
if($result['status'] != TRUE) {
$CI->session->sess_destroy();
$CI->session->set_flashdata('flashError', 'User not active, please contact your administrator');
redirect(site_url(), 'refresh');
}
}
According to the codeignitier's documentation,
All session data (including flashdata and tempdata) will be destroyed
permanently and functions will be unusable during the same request
after you destroy the session.
So my suggestion to you to remove all the session data except the important ones.
$user_data = $this->session->userdata();
foreach ($user_data as $key => $value) {
if ($key!='__ci_last_regenerate' && $key != '__ci_vars')
$this->session->unset_userdata($key);
}
Don't destroy the session. Use unset_userdata() to unset your unwanted session. $this->session->unset_userdata('session_name'); It may solve your problem. For additional server request you can use $this->session->keep_flashdata('session_name')

PHP Session does not work properly [Edited:code attached]

Edited:
I am too sad that this question was downvoted, I was stuned by this for many hours.I wish there are a lovely alchemist who can make me back from debuff condition.
I am using codeigniter,I think the problem is when the new session (the session with flash message) is set, the session id (as a cookie) does not send to client, so after redirect to other pages, a fresh new session is created.
There is a problem in my log out function. The logic is simply click "log out", redirect to index page with a flash message--You have been log out.
After inspect, I found these things:the old session is clear with no problems, the new session is created before redirection, the new session do has flash message. Then the strange things comes, when redirected to index, a fresh newer session is created. But, If I do not run redirection after adding flash message, and click browser's refresh, then go to index manually, the session with flash message will be there and displayed perfectly.
I also found before redirection or refresh browser, though the session is recreated, there is no session id in my cookies. The refresh action sends session id to my cookies.
I hope I made the question clear. Thank you.
//auth controller
public function logout()
{
$this->my_auth_lib->logout();
$this->session->set_flashdata('alert','You have been logged out!');
redirect('index');
}
//my_auth_lib
public function logout()
{
return $this->session->sess_destroy();
}
// session library sess_destory method
public function sess_destroy()
{
// get session name.
$name = session_name();
if (isset($_COOKIE[$name])) {
// Clear session cookie
$params = session_get_cookie_params();
setcookie($name, '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
unset($_COOKIE[$name]);
}
$this->sess_create();
}
//session library sess_create method
public function sess_create()
{
$_SESSION[$this->sess_namespace] = array(
'session_id' => md5(microtime()),
'last_activity' => time()
);
// Set matching values as required
if ($this->_config['sess_match_ip'] === true) {
// Store user IP address
$_SESSION[$this->sess_namespace]['ip_address'] = $this->ci->input->ip_address();
}
if ($this->_config['sess_match_useragent'] === true) {
// Store user agent string
$_SESSION[$this->sess_namespace]['user_agent'] = trim(substr($this->ci->input->user_agent(), 0, 50));
}
$this->store = $_SESSION[$this->sess_namespace];
}
Try putting an
exit;
statement in the line right after the redirect
Got the idea from here
PHP: session isn't saving before header redirect

How to store sessions with PHP

I am trying to create a PHP session class to store sessions. What is the best way to deal with sessions?
This is what I have so far:
class Sessions {
function start() {
session_start();
$_SESSION['sid'] = randomstring();
// insert session id into db
// initialize user data
}
function destroy() {
session_destroy();
// delete sid from db too
}
function update() {
session_regenerate_id();
// update lastaccess time in db
}
}
What is the best way to store sessions in PHP?
This will answer your question of Session Handling? http://www.devshed.com/c/a/PHP/Storing-PHP-Sessions-in-a-Database/

Categories