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.
Related
I have a simple website where you need only a password to access the contents. Then there are 3 fields where user inputs data, which are then stored in cookies. In the end - there is a logout script that resets the session and unsets cookies.
Please find the relevant code below:
Login page (index)
<?php
session_start();
$password = '';
$wrongPassword = '';
if (isset($_POST['sub'])) {
$password = $_POST['login_passcode'];
if ($password === 'PASSCODE') {
$_SESSION['login'] = true;
header('LOCATION:/personal.php');
die();
} else {
$wrongPassword = true;
}
}
if (isset($_COOKIE['m_username'])) {
header('LOCATION:/personal.php');
die();
}
?>
The page with contents, where user inputs name, department and start date
<?PHP
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header("Location:/index.php");
die();
}
?>
and the logout script:
<?PHP
session_start();
if (isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_username'])):
setcookie('marriott_username', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_startdate'])):
setcookie('marriott_startdate', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_department'])):
setcookie('m_department', '', time() - 7000000,'/');
endif;
$_SESSION = array();
session_destroy();
header ("Location:/index.php");
die();
?>
jQuery to create cookies below:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Cookies do expire (at least on chrome), however after trying to access website after a few hours or days, I get the error about too many redirections. I believe this might be due to some differences between session expiration time and cookies expiration time (5 days for cookies), but I don't really know where to start fixing these...
Also, on Internet Explorer (IE8) the redirects problem occurs even when I go through logout directly.
Will be grateful for any help,
E.
You are correct in thinking different cookie expirations are behind the too many redirects problem.
If isset($_COOKIE['m_username']) is true in the index page, then you are redirected to the personal page, in which if if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) is also true, it sends you back to the index, therefore creating a loop. This would be caused by the session cookie expiring before the cookies you set.
The $_COOKIE and $_SESSION superglobals refer to two different sets of cookies. One solution is to use just the PHP session and store all your session data in the $_SESSION superglobal.
For example:
$_SESSION['m_username'] = 'whatever_value';
This will however generate an overhead in extra memory usage. If you still want to use your own cookies then just make sure any logic determining redirects is based on the session, not the presence of cookies you set.
For example:
// When logging in
$_SESSION['logged_in'] = true;
// On every page that requires login
if(!$_SESSION['logged_in']) // Redirect
In my PHP project, I want to add a user remember me checkbox so that everybody can choose to stay logged in:
Until now I do my normal log in like:
public function loginUser($psMail, $psPwd, $pnRememberMe = 0) {
// Check credentials and so on
// If mail and password matches
if(CREDENTIALS OKAY) {
$_SESSION["username"] = "foo";
$lnExpire = time() + 3600 * 24 * 60;
setcookie("remember", base64_encode(USERID), $lnExpire);
setcookie("rememberToken", md5(SOMESTUFF), $lnExpire);
}
}
When I log in, I can see the created cookie variables with:
print_r($_COOKIE);
Now I try to leave the site with my logout function:
// Unset the session variables
$_SESSION = array();
// Destroy the session.
session_destroy();
But now, when I am at the landing page, there are also my cookies gone?
Could this be because of my session site settings?
ini_set("session.use_only_cookies", "1");
ini_set("session.use_trans_sid", "0");
php function setcookie has fourth argument path, from documentation "The path on the server in which the cookie will be available on". By default it set path to actual your directory. Try set "/" Then it will be available for all domain. http://php.net/manual/en/function.setcookie.php
Try this code hope it will work for you
if(count($_POST>0) && isset($_POST['checkbox']))
{
setcookie('name',$_POST['uname'],time()+3600);
setcookie('password',$_POST['pw'],time()+3600);
}
elseif(count($_POST)>0)
{
setcookie('name','',time()-3600);
setcookie('password','',time()-3600);
}
if(count($_POST)>0 && $_POST['uname']!="" && $_POST['password']!="")
{
if(isset($_COOKIE['name']) && isset($_COOKIE['password']))
{
echo $_COOKIE['name'];
echo $_COOKIE['password'];
}
your login detail code here.....
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'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 "/"