Session is not being destroy in codeigniter - php

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);

Related

Codeigniter Auth system based on device

I am kind of newbie around here so hope i am doing fine what am i doing.
I started working with Codeignter recently and trying to build a secured login to restrict access from three devices only.
On login
I am trying to add a never-expiring "device_id" cookie upon successful authentication. That cookie would be a a unique string and store it into database
And if the user has aleady three devices stored to be rejected.
If the user has available devices slots, this to be recorded and added to its stack.
Basicly i want to allow access if the user has avail slots or the cookie arleady exists.
Have any ideea where should i start or there is a Codeigniter library ?
The code from my control that alows and valides login is:
function login()
{
if ($this->session->userdata('logged_in'))
{
$logged_in_user = $this->session->userdata('logged_in');
if ($logged_in_user['is_admin'])
{
redirect('admin');
}
else
{
redirect(base_url());
}
}
// set form validation rules
$this->form_validation->set_error_delimiters($this->config->item('error_delimeter_left'), $this->config->item('error_delimeter_right'));
$this->form_validation->set_rules('username', lang('users input username_email'), 'required|trim');
$this->form_validation->set_rules('password', lang('users input password'), 'required|trim|callback__check_login');
if ($this->form_validation->run() == TRUE)
{
if ($this->session->userdata('redirect'))
{
$redirect = $this->session->userdata('redirect');
$this->session->unset_userdata('redirect');
redirect($redirect);
}
else
{
$logged_in_user = $this->session->userdata('logged_in');
if ($logged_in_user['is_admin'])
{
redirect('admin');
}
else
{
redirect(base_url());
}
}
}
// setup page header data
$this->add_css_theme( 'login.css' );
$this->set_title( lang('users title login') );
$data = $this->includes;
// load views
$data['content'] = $this->load->view('user/login', NULL, TRUE);
$this->load->view($this->template, $data);
}
it's not a good idea to write your system ....you can not secure your auth system from session hijacking (when session_id not change in long period) , dos attack , ddos attack , etc very easliy .... it's better to use early written system like auth_ion ....
you can find authentication library for code igniter in :
https://github.com/bcit-ci/CodeIgniter/wiki/Contributions#libraries
i preffer ion_auth in that list ...

Codeigniter destroy sessions separately

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();
}

codeigniter session lost when refresh (F5)

First of all i'm new for codeigniter. All i want to ask is, why every refresh my session data is lost. i redirect to login.
Here is my code.
login controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->helper('form');
$this->load->view('login');
}
}
?>
verifylogin
function index() {
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
//$this->load->view('headerx');
//redirect('login', 'refresh');
$this->load->view('login');
}
else {
//Go to private area
redirect('home');
}
}
function check_database($password) {
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result) {
$sess_array = array();
foreach($result as $row) {
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
?>
home controller
function index()
{
if($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('home', $data);
}
else {
//If no session, redirect to login page
// print_r($this->session->all_userdata());
//die();
redirect('login');
}
}
first login it is success, but when i refresh (f5) it is back to login form.
my opinion its because session is lost.
thanks for any help...
EDIT AND SOLVED :
sorry for inconvenience, this problem happen because
<script>
function goOut(){
<?php $this->session->unset_userdata('logged_in');?>
window.location="<?php echo base_url()?>";
}
</script>
my purpose it is when click button logout, then session is unset, but if i input in the header, session will be lost again, so i will find another way. thank you for your attentions and help.
I would try using CodeIgniter's sessions in the database instead. I've had problems with CI in the past with this sort of problem. It usually occurs when you're setting a large amount of data (greater than 4KB) in the cookie.
Let me know if database-based sessions is not an option.
See here for more information: CodeIgniter Sessions See heading "Saving Session Data to a Database"
If you are on windows there is an issue with Codeigniter, PHP 7, and Apache on Windows 10. I had a client who wanted the staging application on their own laptop, and this only happened on their new laptop.
So after hours of testing, we uninstalled XAMPP 7.1.4, and reinstalled XAMPP with version 5.6.XX. And that fixed it. Yet, there were no issues on Linux boxes running Nginx and PHP 7. Just Windows 10.
Anyway, I hope this helps! It took me hours to find the solution.

codeigniter redirect fails only when i include "refresh"

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller
{
public function __construct()
{
parent::__construct();
//Model for fetching users in database
$this->load->model('user', '', TRUE);
}
public function index()
{
//Load method to help verify form credentials
$this->load->library('form_validation');
//-----------------------------------------------
//Verify Existance of values in login form fields
//-----------------------------------------------
//Validate existance of username field value
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
//Validate existance of password field value, and if exists then call 'check_database' func
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
//If the form validation is false (i.e. Missing form fields)
if($this->form_validation->run() == FALSE){
//Redirect back to login page
$this->load->view('general-Login');
}
//Login Success, goto main-page
else{
//Go to main page
redirect('Main', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//Check the username and password against database
$result = $this->user->login($username, $password);
//If there is a result
if($result){
//will be used for session information
$sess_array = array();
foreach ($result as $row){
$sess_array= array(
'id' => $row->id,
'username' => $row->username
);
//Session set as logged in
$this->session->set_userdata('logged_in', $sess_array);
}
return true;
}
//No existance of user or, incorrect password
else{
//Send Message of incorrect username or password
$this->form_validation->set_message('check_database', 'Invalid Username or Password');
return false;
}
}
}
So i have a verifylogin controller that handles the form data from my login page. Database access works great and everything works perfectly until i get to the redirect feature. I try to redirect with refresh and it just gives me a page that says "undefined". Now it will suddenly work when i remove the 'refresh' and just leave the controller name, but i'm trying to figure out why this 'refresh' won't work.
I've disabled my .htaccess
I've tried setting my $config['uri_protocol'] to REQUEST_URI, AUTO, and PATH_INFO
and had no luck.
Also, this is my first submission online to anything like a forum so please....be gentle.
First off, welcome to Stack Overflow.
Secondly, if redirect() without the "refresh" works, I would run with it and figure it out later.
For a deeper explanation, "refresh" attempts to do a meta-like refresh to the page similar to:
<meta http-equiv="refresh" content="0;URL='http://example.com/'">
(Note: It doesn't do that within your view, but rather sends the browser a similar snippet in the response)
What browser are you using? What version? Hopefully it's something up-to-date, because that could make a difference in how the refresh works.
I had similar problem. E.g. on my localhost refresh do not work and on the hosting provider settings it works. Maybe something in Apache/PHP configuration. Go without refresh, it is OK. I do not think it has something to do with a browser. I was using the same browser when that happened.

CodeIgniter function to clear session

If i uncomment this code, i get blank page at site. If i comment this, site works.
Here is my exit code (auth by sessions):
function exit($action='') {
if ($action == "true") {
echo "Exit.";
return;
}
$login = $this->session->userdata('username');
if ($login == NULL) {
redirect('/blog/login/', 'location', '301');
}
$array_itmes = array('username' => "$login");
$this->session->unset_userdata($array_items);
redirect('/blog/exit/true/', 'location', '301');}
after normal login:
$newdata = array('username' => "$name");
$this->session->set_userdata($newdata);
in other actions i using:
$login = $this->session->userdata('username');
if ($login !== NULL) {
echo $login;
}
and I get my username. where is an error in first code? i`m from Russia, so sorry for bad English.
Just replace it with $this->session->sess_destroy();
$array_val = array('userid' => '','username' => '', 'email' => '');
$this->session->unset_userdata($array_val);
This is remove individual session details.
Anton's answer will destroy whole session at once. If you would want to delete entire session data use this like Anton said,
$this->session->sess_destroy();
But if you would want to only destroy specific user data use below,
$this->session->unset_userdata('user_name');
Hope this helps, thanks!!
Happy coding!!
To clear the current session (for example, during a logout), you may simply use either PHP’s session_destroy() function or the sess_destroy() method. Both will work in exactly the same way:
session_destroy();
// or
$this->session->sess_destroy();
you can also use
session()->destroy();
it clears the session buffer so you get the logging out effect.

Categories