cookie unset not working properly - php

I am using remember option in my login page.I think I am doing right but when in logout I just amn't able to unset the cookie variable.I am using CI but for cookie I am using native cookie.What am I doint wrong?My code:
in login controller:
function index(){
if(isset($_COOKIE['remember_me'])){
redirect('index');
}elseif($this->input->post()){
$username = $this->input->post('username');
$password = $this->input->post('password');
$remember = $this->input->post('remember');
if($remember){
$time = time()+60*60*24*365;
setcookie('remember_me', $username , $time);
}
$this->session->set_userdata('user_name', $user_name);
$this->session->set_userdata('full_name', $full_name);
$this->session->set_userdata('server', $server->exchange_server);
redirect('index');
}else{
$this->load->view('login');
}
}
function logout(){
$this->session->unset_userdata('user_name');
$this->session->unset_userdata('full_name');
$this->session->unset_userdata('server');
$data['login'] = 'Logout Successfully.';
$data['class'] = 'success';
$this->session->set_flashdata($data);
/* To unset cookie i tried following different approach but to no avail*/
setcookie('remember_me');
setcookie('remember_me', '', $time()-60*60*24*365);
setcookie('remember_me', false);
unset($_COOKIE['remember_me']);
redirect('login');
}
but to no avail. I just can't unset cookie and when user who has checked remember me option trys to logout it's not happening.
Any help/suggestion is welcome.Thanks
I don't know what is the problem but I used jquery plugin for cookie delete {https://github.com/carhartl/jquery-cookie}. I included jquery.cookie.js and then on logout click I deleted the cookie set as $.removeCookie('remember_me')

with
unset($_COOKIE['some_cookie'])
you don't delete the Cookie on the browser, you unset the variabile $_COOKIE['some_cookie'].
If you want delete the browser cookie you have to set the expiration date in the past:
setcookie("some_cookie", "", time()-3600);
If it doesn't work try setting properly the cookie domain.
Create:
setcookie('some_cookie', null, time() + 3600, "/");
Delete:
setcookie('some_cookie', null, time() - 3600, "/");

I don't know what is the problem but I used jquery plugin for cookie delete {https://github.com/carhartl/jquery-cookie}. I included jquery.cookie.js and then on logout click I deleted the cookie set as $.removeCookie('remember_me') and it's working fine.Thanks for the suggestions and help.

Use this function please
delete_cookie()
And for native php cookie use
unset($_COOKIE['remember_me']);
Or use CI function as follows
setcookie('remember_me', null, -1);
That's all

Related

PHP - Cookie and Session Doesn't get Deleted Permanently

I trigger the function below in all my web pages.
function refresh_user_auth() {
if (isset($_COOKIE["UserID"])) {
$_SESSION["UserIDS"] = $_COOKIE["UserID"];
setcookie("UserID", $_COOKIE["UserID"], time() + (86400 * 30), "/");
}
elseif (isset($_SESSION["UserIDS"])) {
$_SESSION["UserIDS"] = $_SESSION["UserIDS"];
setcookie("UserID", $_SESSION["UserIDS"], time() + (86400 * 30), "/");
}
}
I use the function below to log out but it doesn't seem to have logged me out when I visit other web pages on the website.
function unset_user_auth() {
if (isset($_COOKIE["UserID"])) {
unset($_COOKIE['UserID']);
$_COOKIE = array();
setcookie('UserID', '', time() - 36000);
}
if (isset($_SESSION["UserIDS"])) {
unset($_SESSION['UserIDS']);
$_SESSION = array();
session_destroy();
setcookie('UserIDS', '', time() - 36000);
}
}
Please, what am I doing wrong?
I'm not sure why you have to do that separately for cookie and session, you can do that all at once. When logging out, it isn't required to check if cookies are set and/or session is set if you're going to destroy both anyway (unless you have an option to save cookie for 'Remember me' function).
Here's an example from a comment in the PHP documentation for session_unset() function page. You could always refer to PHP documentation when in doubt. You'll find ample examples and use cases in the comments.
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
?>

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

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

Is anything other than unset($_SESSION) needed for logout?

Is there any reason that unsetting the session wouldn't be enough for a logout? Is there some security reason more is needed?
I have a script that uses the facebook login (using PHP). But for some reason, using any of the following messes with the login for some reason. After being logged out using any of the codes below, when trying to login using facebook redirect it it forces you to push the button twice for it to recognize that a facebook session has been created.
if (isset( $_COOKIE[session_name()] )) {
setcookie(session_name(), "", time() -3600, "/" );
}
$_SESSION = array();
session_destroy();
Try something like below:
$params = array('next' => 'http://something.com/logout.php');
$logout = $facebook -> getLogoutUrl($params);
$_SESSION['logout'] = $logout; `

php set session with cookies

$_SESSION['user_id'] = $login;
setcookie('user_id', '$login' , time()+86000);
header('Location: userindex.php');
function logged_in() {
return (isset($_SESSION['user_id']) || isset($_COOKIE['user_id']) ? true : false;
}
I have SESSION but I wonna include COOKIE too but I don't know how to restart SESSION with COOKIE. I don't have a idea how I can get that. I create COOKIE but can't logout and have problem with SESSION somebody can help me to fix my problem???? And in every page on top I have logged_in function for check if user is logged in or not I wonna these logged_in function to check if user has cookie to auto login to user cookie. I think it is in logged_in function must get write some code and...
I will note that this is not secure, as any one can create the cookie, using something like firebug.
#session_start();
function logged_in() {
if(!isset($_SESSION['user_id']) && isset($_COOKIE['user_id'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
}
return isset($_SESSION['user_id']);
}
function logout() {
unset($_SESSION['user_id']);
setcookie("user_id", "", time() - 3600);
header("Location: http://".$_SERVER['HTTP_HOST']);
exit;
}
Edit: Added logout() - will remove both session and cookie 'user_id', then redirect to homepage
First: you should set it with:
setcookie('user_id', $login , time()+86000);
So $login without quotes. And also maybe set path variable if this cookie should be seen in different pages.
Removing cookie is done with setting negative time value:
setcookie('user_id', '' , time()-86000);
session_start();
function logged_in() {
if(!isset($_SESSION['user_id']) && isset($_COOKIE['user_id'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
}
return (isset($_SESSION['user_id'])) && isset($_COOKIE['user_id'])));
}

Categories