CodeIgniter function to clear session - php

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.

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

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

Unable to validate user login via code igniter

I've been rebuilding my site with code igniter and am having trouble validating the users info. To put it simply, I can type in gibberish to my login form and it will take me to the 'welcome' page no matter what.
Click HERE to view my code
Thanks in advance.
Not sure if you have more than one problem, but this is definitely one of them:
if($query->num_rows = 1) {
That should be:
if($query->num_rows() == 1) {
What does $this->login(); do in the model?
Anyways, this seems to work correctly for me:
Model:
public function validate($email, $password) {
if ($email == 0 || $password == 0) return false;
//SEE IF THEIR INFO IS IN THE DB
$this->db->where('email', $email);
$this->db->where('password', $password);
$query = $this->db->get('users');
return ($query->num_rows() == 1);
}
Controller:
public function validate() {
//THIS LOADS THE MODEL THAT TAKES ALL THEIR INFO THEY TYPED AND INSERT IN THE DB
$this->load->model('auth_model');
$this->load->library('session');
$query = $this->auth_model->validate($this->input->post('email'),$this->input->post('password'));
if($query) {
// IF THEIR INFO MATCHES UP, THEN START A SESSION WITH CI'S BUILT IN SESSION CLASS
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password'),
'is_logged_in' => true
);
// AUTO LOADED SESSION CLASS
$this->session->set_userdata($data);
//THIS WILL TAKE THEM TO THE DASHBOARD PAGE IF EVERYTHING CHECKS OUT
redirect('home/dashboard');
} else {
// IF INCORRECT THEN RELOAD THE FORM FOR NOW
$this->index();
}
}
Minboost's answer is definitely something you should fix before proceeding, but the assignment should evaluate to true, and you'd have the opposite problem. People would login no matter what.
Are you storing sessions in the database or with cookies? I've had problems before with setting cookies and then immediately redirecting. Some browsers seem to have issues with the order of the Set-Cookie vs. Location headers. You might try to rule that out before banging your head too hard.
Other possibilities include A) code you're not showing us that might be redirecting back to the login page for some reason, B) routing issues, C) something else you could figure out by tracing the response headers in FireBug.

Destroy Session but keep flashdata

I am using Tank Auth for user management in my CI 1.7.3 App. Everything is working fine but I'm trying to set a flash_message to be displayed when the user logs out. The problem is the $this->tank_auth->logout(); function destroys the session. I have modified the logout function in the Tank Auth library to look like:
function logout() {
$this->delete_autologin();
// See http://codeigniter.com/forums/viewreply/662369/ as the reason for the next line
$user_session_data = array('user_id' => '', 'username' => '', 'status' => '');
$this->ci->session->set_userdata($user_session_data);
$this->ci->session->unset_userdata($user_session_data);
}
It was previously
function logout()
{
$this->delete_autologin();
// See http://codeigniter.com/forums/viewreply/662369/ as the reason for the next line
$this->ci->session->set_userdata(array('user_id' => '', 'username' => '', 'status' => ''));
$this->ci->session->sess_destroy();
}
In My controller I have
function logout(){
if ($this->tank_auth->is_logged_in()) { // logged in
$this->session->set_flashdata('status_message', $this->lang->line('auth_message_logged_out'));
$this->tank_auth->logout();
redirect('');
}
}
If I remove the $this->tank_auth->logout(); function the message shows fine. I'm sure it's a simple session problem
If you try to set flashdata while using a database in the same request after you call sess_destroy(), it won't work (because there is no session to append the flashdata to).
To fix this problem, add $this->ci->session->sess_create(); after the call to sess_destroy(). This works because you're re-creating the session before trying to append data to it. This is the only way to use flashdata after a sess_destroy() if you're using sessions in a database.
The sess_destroy() function destroys also the session flash variables used to pass the message.
U already answered your question, in the library logout() function, you need to replace
$this->ci->session->sess_destroy();
with
$this->ci->session->unset_userdata(array('user_id' => '', 'username' => '', 'status' => ''));
This will not completely destroy the session, only the user data used for login, so I recommend instead, to modify the logout() function in the controller and show the message manually, by passing it to a view.
While this is a workaround, it might do the trick for you...
wherever you're displaying these, I'll be assuming you're checking in the view so...
<? if ($this->session->flashdata('status_messege'): ?>
<p><?= $this->session->flashdata('status_message') ?></p>
<? endif; ?>
you COULD add an elseif to that and check for the referrer being your logout function...
<? if ($this->session->flashdata('status_messege'): ?>
<p><?= $this->session->flashdata('status_message') ?></p>
<? else if ($this->agent->referrer() == site_url('path/to/logout'): ?>
<p><?= $this->lang->line('auth_message_logged_out') ?></p>
<? endif; ?>
A bit of a hackish way to overcome this issue, but probably a way nonetheless.

PHP - Set session within a function

got a (I guess...) very simple problem:
I want to set a session within a function.
Simple situation:
I got a login form. After subimitting the form, I call a function "login" which checks if user has authenticated. If yes, a session should be set.
Here some very simple code:
session_start();
function login() {
$SESSION['login'] = true;
}
if (isset($_REQUEST['doLogin'])) {
login();
// is session is set here, it works...
}
if ($SESSION['login'] === true) echo 'you are logged in';
But this doesn't work. Why?
Thanks alot!
You are using $SESSION you need to be using $_SESSION

Categories