I've got a problem, user can't Log Out because the $_COOKIE's are not actually deleting. I can't find out what could be the problem.
This code is used only once at Log In:
// Log In
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
setcookie('user_id', $row['user_id'], time() + 2592000);
setcookie('username', $row['username'], time() + 2592000);
The code below is checking if cookies are set up to make users to be logged in when they relaunch their browser (the "keep me logged in" effect).
// Starting Session
session_start();
// If the session vars aren't set, try to set them with cookies
if (!isset($_SESSION['user_id'])) {
// This check always equals true because cookies are not deleting on Log Out
if (isset($_COOKIE['user_id']) && isset($_COOKIE['username'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['username'] = $_COOKIE['username'];
}
}
This code is launched only once on Log Out:
// Log Out
session_start();
if (isset($_SESSION['user_id'])) {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 2592000, '/');
}
session_destroy();
}
setcookie('user_id', '', time() - 2592000);
setcookie('username', '', time() - 2592000);
Don't use relative times for cookies. if you want to expire a cookie, then use Jan 1 1970 00:00:00. You're assuming that the user's clock is accurate and within an hour of your server's. Given how many people have their VCRs blinking 12:00, this is a bad assumptiong.
As well, why are you storing login information in a client-side cookie? The only cookie you should really be setting is the session cookie, which session_start() already does for you, then store all that information in $_SESSION only.
I think you're doing it way too complicated.
My example where it's just an admin login:
login.php
#session_start();
if (isset($_GET['login'])) {
if($_GET['name'] == $s['admin']){
if($_GET['pw'] == $s['adminpw']){
$_SESSION['isadmin'] = true;
}
}
}
logout.php
#session_start();
unset ($_SESSION['isadmin']);
use session_set_cookie_params() to set the lifetimes
I found why cookies were not removing!
To make sure your cookies will remove, set the same path on removing cookies as on setting them.
// Setting Cookie
setcookie(session_name(), '', time()-2592000, '/'); // The path here is "/"
// Removing Cookie
setcookie(session_name(), '', time()+2592000, '/'); // The path here is "/"
Related
I'm trying to unset/delete/expire cookies on a logout page. However, it doesn't seem to be working. My logout script reads as follows:
require_once("database.php"); // contains session_start()
$_SESSION = array();
session_destroy();
// attempts to unset cookies go here (see below)
var_dump($_SERVER['HTTP_COOKIE']);
header("Location: ./login.php");
exit();
My three attempts to remove a specific cookie login (or all of them), are as follows:
Attempt 1:
setcookie("login", "", time() -3600, "/");
Attempt 2:
$cookies = explode(";", $_SERVER['HTTP_COOKIE']);
foreach ($cookies as $cookie) {
$parts = explode("=", $cookie);
$name = trim($parts[0]);
setcookie($name, "", time() -3600);
setcookie($name, "", time() -3600, "/");
}
Attempt 3:
unset($_COOKIE);
However my var_dump() still contains the cookies!
Also, the page you're then redirected to, login.php contains the following code:
if (isset($_COOKIE['login'])) {
echo "Still set."
}
and low-and-behold, the page displays Still set.
First of all remove all cookies from any available Cookie tools or your browser's developer tool.
Always write COOKIES as '/' with respect to entire domain of site. Path play an important role when we set/unset cookies. Use
setcookie($cookie_name, "$cookie_value", time() +3600, "/") to set and setcookie($cookie_name, "$cookie_value", time() -360000, "/") to unset COOKIES.
Further read here for about COOKIES path: http://www.w3schools.com/php/func_http_setcookie.asp
Hope it helps you
I'm setting an auth cookie like so:
$identifier = $this->createIdentifier($username);
$key = md5(uniqid(rand(), true));
$timeout = time() + 60 * 60 * 24 * 100;
setcookie('auth', "$identifier:$key", $timeout);
After logout I'm trying to invalidate it by doing this:
setcookie('auth', "", time() - 3600);
When I try to view a restricted page after logging out I'm checking to see if the cookie exists:
if (isset($_COOKIE['auth'])) {
error_log("COOKIE EXISTS: " . print_r($_COOKIE, true));
}
Here is my logout script:
if (!isset($_SESSION)) session_start();
$ref="index.php";
if (isset($_SESSION['username'])) {
unset($_SESSION['username']);
session_unset();
session_destroy();
// remove the auth cookie
setcookie('auth', "", time() - 3600);
}
header("Location: " . $ref);
exit();
I shouldn't be hitting this code but I am. After logging out I see the cookie has been removed from my browser. Any idea how it's finding it again after logging out?
UPDATE
This code get called from another class that checks user privs etc. The only files it doesn't work with are files that reference it from one directory above. For instance
Any file referencing it like this works OK:
<?php include_once('classes/check.class.php');
Any file referencing it like so DO NOT work:
<?php include_once('../classes/check.class.php');
Any thoughts what might be causing this?
After you log the user out you need to do a redirect to cause a new page load. Since cookies are sent with page requests until a new requests is made those cookies are still alive even after you "delete" them.
I have this code that setted when login check is fine:
if((isset($_POST["remember_me"]))&&($_POST["remember_me"]==1))
{
setcookie('email', $username, time()+3600);
setcookie('pass', $pass, time()+3600);
}
Now, when I click on logout link (logout.php)
i did this:
<?php session_start();
setcookie("email", '', 1, "");
setcookie("pass", '', 1, "");
$_SESSION["login"] = "";
header("location: aforum/enter_furom.php");
?>
I didn't use destroy session because I don't want to destroy all sessions....
now destroying a session is working fine... but when I try to unset cookies, the browsers (all browsers: explorer, chrome, firefox, mozilla) give me an error saying that the new cookies cant be setted...any help to unset the above cookies ?
either use the superglobal _COOKIE variable:
unset($_COOKIE['mycookiename']);
or call setcookie() with only the cookies name
setcookie('mycookiename');
To reset your cookies at logout use:
setcookie('pass');
setcookie('email');
For you login check:
if(
isset($_POST["remember_me"]) &&
$_POST["remember_me"]==1 &&
$_COOKIE['pass'] != NULL &&
$_COOKIE['email'] != NULL &&
)
setcookie('cookiename', '', time()-3600);
unset($_COOKIE['MYCOOKIE']);
//
setcookie('MYCOOKIE', '', -1, '/');
Care for header "Cannot modify header information.." you can also
use html or javascript for redirect
header("Location: /");
//
echo '<meta http-equiv="refresh" content="0;URL=/">';
//
echo '<script>window.location.replace("/");</script>';
I prefer to check with isset and than unset | setcookie
if(isset($_COOKIE['MYCOOKIE'])) { unset($_COOKIE['MYCOOKIE']); }
//
if(isset($_COOKIE['MYCOOKIE'])) { setcookie('MYCOOKIE', '', -1, '/'); }
this seems to work too, but don't use it in my opinion
setcookie('MYCOOKIE', '', -1, '/') ?? '';
!isset($_COOKIE['MYCOOKIE']) ?: setcookie('MYCOOKIE', '', -1, '/');
Check in your browser for the directory where the cookie operates. And unset it by specify the path the cookie have. Like in the example if the cookie directory is /aforum/
setcookie ("email","",time()-1,"/aforum/","http:// yourdomain.com");
Just set the value of cookie to false in order to unset it,
setcookie('cookiename', false);
That's the easiest way to do it.
To unset cookies in PHP, simply set their expiry time to a time in the past. For example:
$expire = time() - 300;
setcookie("email", '', $expire);
setcookie("pass", '', $expire);
try this
setcookie ("email", "", time() - 3600);
setcookie ("pass", "", time() - 3600);
You need to set your expire time to the past, e.g.
setcookie('email', '', time()-3600);
Also you should be using an Absolute URI for your header('Location:' ....).
In Chrome and IE8+ at least, the following will remove the cookie from the browser. It will not be reflected in the $_COOKIE array until the page is reloaded however.
setcookie('cookiename','',0,'/',$cookieDomain)
you may be able to leave off a few parameters here, but the important thing is you are setting an empty string, and that removes the cookie from the browser.
I have a login/logout system and need the cookies to work across www.mydomain.com as well as mydomain.com. The problem I'm having is on deleting the cookies. On the login I am setting the cookies like this:
session_start();
//set session vars
setcookie('user_id', $row['user_id'], time() + (60 * 60 * 24 * 30), '/', 'domain.com');
setcookie('full_name', $row['first_name']." ".$row['last_name'], time() + (60 * 60 * 24 * 30), '/', 'domain.com');
Which works, and the cookies are saved and it works with or without the www. It allows the profile page to be viewed which has this code:
session_start();
if(!isset($_SESSION['user_id'])) {
if(isset($_COOKIE['user_id']) && isset($_COOKIE['full_name'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['full_name'] = $_COOKIE['full_name'];
}
}
if(!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
The problem is logging out:
session_start();
if(isset($_SESSION['user_id'])) {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600, '/', 'domain.com');
}
session_destroy();
}
setcookie('user_id', '', time() - 3600, '/', 'domain.com');
setcookie('full_name', '', time() - 3600, '/', 'domain.com');
The cookies are deleted but only for the current domain. So if I login from domain.com/login.php and logout from domain.com/logout.php, domain.com/profile.php doesnt work (good) but I will still be able to view www.domain.com/profile.php if I have visited the www. version before logging out. And vice versa I can logout from www.domain.com/logout.php and still be able to view domain.com/profile.php. Is there a way to delete all cookies across the subdomains?
Use '.domain.com' instead 'domain.com' to work with all subdomains.
The OP wrote in a comment:
Finally figured it out, the session was creating a separate cookie when the subdomain was changed. So logging out would delete one session cookie but leave the other. The solution was to name the session before starting it so it always has the same name:
$some_name = session_name("cool_session");
session_set_cookie_params(0, '/', '.domain.com'); session_start();
I use the following codes to log users out from a web app. while logging in I set cookie email and password, but after logging out, visiting the home page automatically logs the user in again, probably because the cookie wasn't successfully destroyed. Please how do I get it right. Here is log out code
function log_out() {
$old_user = $_SESSION['valid_user'];
unset($_SESSION['valid_user']);
unset($_SESSION['login']);
unset($_SESSION['blog_addr']);
$result_dest = session_destroy();
setcookie('email', '');
setcookie('pswd', '');
if (!empty($old_user))
if ($result_dest)
return true;
else
$msg = 'Could not log you out ';
else
$msg = 'You have not been logged in so you are not logged out ';
return $msg;
}///:~
You need to set setcookie to an expiration date in the past. See the example here:
http://php.net/manual/en/function.setcookie.php
Try setting the cookie expiration for some time in the past:
setcookie ("email", "", time() - 3600);
How did you set up your cookie? ( logging in ).
In general setting a cookie off , you have to go back in time !
setcookie("email", "",time()-3600,'/');
In addition to other comments. You've set $_SESSION['valid_user']; to $old_user before you did an unset, so you should't be checking for $old_user as it contains the old data. you should't even need to set those to any variables. Also you should be using brackets.
function log_out() {
unset($_SESSION['valid_user']);
unset($_SESSION['login']);
unset($_SESSION['blog_addr']);
session_destroy();
setcookie('email', '', time() - 3600);
setcookie('pswd', '', time() - 3600);
if (!isset($_SESSION['valid_user'])){
if ($result_dest) // don't know what this does.
return true;
else
$msg = 'Could not log you out ';
}
else
$msg = 'You have not been logged in so you are not logged out ';
return $msg;
}
Try to delete the cookies by doing this:
setcookie ("email", "", time() - 3600);
setcookie ("pswd", "", time() - 3600);
This will delete the cookies by setting their expiration date in the past.