I'm struggling over an hour on how to delete cookies. I found out that to delete a cookie, its value must be set to past, so it expires. However if I try with time()-something or even time() nothing is done to cookie. However setting expiration time to time()+1 works. But I'd like to have the cookie deleted immediately. Not after 1 second.
So this works:
if (isset($_COOKIE['rememberme'])) setcookie('rememberme', 'del', time()+1, '/', 'localhost');
This doesn't do anything to the cookie, leaving it as it was before logout:
if (isset($_COOKIE['rememberme'])) setcookie('rememberme', 'del', time()-1, '/', 'localhost');
I think it is my browser's fault. If expiration time is set to past it displays the old cookie as it was before log out, however my script acts like this cookie doesn't exist. The browser is Iceweasel (Firefox on Debian).
Related
I am having problems with the buildin session functionality of php.
When I start the session the client recieves the session cookie as it is supposed to. But the cookie never gets send back to the server.
All other cookies get send (checked that multiple times). The host is correct and the path aswell.
The php.ini file seemed correct.
I also tried renaming the session cookie without success!
I want to add that every time I access the site I get another session cookie.
Also when I debugged this I added this line error_log(print_r($_COOKIE, true)); as the first line of my code. Still no session cookie.
Here is some code I'm using:
// This function exists so that I only start the session once.
function start_session() {
if(session_id() == "") {
session_start();
setcookie(session_name(), session_id(), time() + ini_get("session.cookie_lifetime"));
// The client gets this cookie!
}
}
start_session();
session.cookie_lifetime in my php.ini is 0. Might this be the cause?
I have no idea what might causing this.
The cause is time() + ini_get("session.cookie_lifetime") with session.cookie_lifetime being 0. Meaning the cookie will expire immediately.
Setting the session.cookie_lifetime to something like 3600 worked.
So i've tried multiple other "solutions" to my problem (both on this site and others) and cannot find a solution that works for me.
I'm trying to set a cookie to log in my user and then on log out delete that cookie. Here is my code.
list ($check, $data) = check_login($dbc, $_POST['Username'], $_POST['Password']);
if ($check) {
setcookie('Username', $data['Username'], time() + 60*60*24*90);
header('Location: RedirectPage.php');
Which, checks the username and password have been entered on the login form (and accepted), If so, the cookie "Username" is set with the username drawn from the database, and a time equalling 90 days, and the user is then redirected.
This part works fine, it logs the user in as would be expected.
However in the delete part,
header('Refresh: 0;');
setcookie('Username', '', time() - 60*60*24*90);
unset($_COOKIE['Username']);
require ('RedirectPage.php');
redirect_user();
I delete the cookie in the same way it was set, as expected, removing any data and setting the time to a negative value, and then for good measure i run the unset cookie to ensure that it has gone.
Except, this doesn't work. setcookie (to delete) does not do anything, and unset cookie only works on the page after it has been run (in this case, index.php) and as soon as i click to another page, or refresh the page it "forgets" that the cookie has been deleted.
Now going into the Chrome inspect element to check the cookie i get
Username, "Value" (the withdrawn username), r3gamers.com (domain), / (path), 2015-02-03T13:45:00 (Expires/MaxAge), 19 (Size) and HTTP and Secure are both set as empty.
Watching the process after hitting the logout button, this cookie is never deleted. The only thing which can actually delete the cookie is overwriting it with a new cookie (logging in again) or deleting it through inspect element.
Any ideas? As far as i'm aware, i'm doing everything that should be done.
EDIT:
I'd also like to mention that when testing this on localhost, offline through netbeans this functionality does work. However when i upload the pages to godaddy for my website they stop working properly.
I found the answer. It's a stupid answer too. Here is the full code file i was using for logout.
<?php
require_once ('Connection.php');
header('Refresh: 0;');
if (!isset($_COOKIE['Username'])){
header('Location: LoginFunctions.php');
} else {
setcookie('Username', '', time()-60*60*24*90, '/', '', 0, 0);
unset($_COOKIE['Username']);
header('Location: index.php');
}
?>
The problem, which i can't show here, was that the opening php tag had a single line break on it, meaning that it started on line 2. Why it was like this initially i don't know, but that small error meant that it worked on localhost and didn't work on godaddy. How frustrating. At least i've fixed the problem now.
For future use, for those stuck with the same issue, apparently godaddy (or most hosting sites) require that any cookie adding, editing or deleting occur from line 1 onwards, therefore the php tag which includes the cookie must be on line 1, no html code can preceed this php tag, or any line breaks, the php tag has to start on line 1.
You do not set the path of your cookie, I assume you want it to be site-wide, so you should set the path to '/':
setcookie('Username', $data['Username'], time() + 60*60*24*90, '/');
And then, when unsetting it, try using 1 instead of time() - 60*60*24*90 (also still specifying the path), otherwise the expiration time of the cookie might vary depending on the user's computer clock:
setcookie('Username', '', 1, '/');
I think your problem really is the path not being set: http://php.net/manual/en/function.setcookie.php
If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
The thing is, if you are in /logout/doit.php, and you try to set the cookie expiration time to a negative value, it will create a new cookie with the path '/logout/' and set its expiration time. (Instead of setting the expiration time on your site-wide cookie)
I'm trying to make my login sessions last longer, so that people don't get logged out of my website too early. For example, making a blog post and losing it when they submit because php expired their cookie.
Ideally I'd like to give them say a 2 hour session where they won't be logged out, which will refresh every time they load the page (this code snippet below is before the header of each secure page)
This is what I am trying, but it comes up with an error for the setcookie() saying that there was a division by zero? What am I doing wrong here?
//How long sessions last
$hours = 2;
// php.ini setting required for session timeout.
ini_set('session.gc_maxlifetime',$hours*60*60);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
//Set the session parameters and start session
$sessionCookieExpireTime=$hours*60*60;
session_set_cookie_params($sessionCookieExpireTime);
session_start();
// Reset the expiration time upon page load
if (isset($_COOKIE[session_name()]))
{
setcookie(session_name(), $_COOKIE[session_name()], time() + $sessionCookieExpireTime, "/");
}
EDIT: Now working as the problem was non-standard quotes and apostrophes. Just in case anyone copies this code and uses it. Code above works now thanks!
If you would like you could add this for when your cookie expires:
time()+60*60*24*30
This is like saying that the cookie expires in 60secs, 60mins, 24h and so on. You should also check out a tutorial on cookies here: http://www.w3schools.com/php/php_cookies.asp
<?php
session_start();
$_SESSION['logged_in'] = false;
setcookie("dsgpassword127", $password, time()-3600); /* expire the cookie */
setcookie("dsgemail127", $email, time()-3600); /* expire the cookie */
session_destroy();
header("location: index.php");
?>
The code above which works very well in Chrome will not remove the cookies in FireFox 14.0.1. I am wondering why this is, if anyone has experienced the same problem or if there is a solution to this conundrum I am in when it comes to expiring these cookies....
According the manual for sesion_destroy():
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. ...If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.
Hard to explain why Chrome is unsetting the cookie, but it's Chrome's behavior that appears to be aberrant, not that of Firefox.
But the presence of an old cookie pointing to a dead session should not be problematic. The server should create a new session - with empty session data - and send back a cookie pointing to the new session.
In fact, saving unencrypted users and passwords on the client is probably ill-advised. Are you sure you need that? Storing that info on the server-side is probably more common, with the client-side only given his the session cookie.
I uninstalled FireFox and reinstalled the latest version which is 15.0. This time when FireFox asked me to remember the password automatically I requested it not do so. Now the browser is reacting normally. I suspect that the same would have been the case also in 14.0.1 in regards to the "Remember password" feature.
Just set the cookie expiration to 1 like so:
setcookie("dsgpassword127", $password, 1); /* expire the cookie */
setcookie("dsgemail127", $email, 1); /* expire the cookie */
Basically the third parameter is the number of seconds since epoch. 1 sets it to 1 second after epoch and so there is not need to worry about time() and all. Check if that helps in firefox.
OK, I'm stumped, and have been staring at this for hours.
I'm setting a cookie at /access/login.php with the following code:
setcookie('username', $username, time() + 604800, '/');
When I try to logout, which is located at /access/logout.php (and rewritten to /access/logout), the cookie won't seem to unset. I've tried the following:
setcookie('username', false, time()-3600, '/');
setcookie('username', '', time()-3600, '/');
setcookie('username', '', 1, '/');
I've also tried to directly hit /access/logout.php, but it's not working.
Nothing shows up in the php logs.
Any suggestions? I'm not sure if I'm missing something, or what's going on, but it's been hours of staring at this code and trying to debug.
How are you determining if it unset? Keep in mind that setcookie() won't remove it from the $_COOKIE superglobal of the current script, so if you call setcookie() to unset it and then immediatly print_r($_COOKIE);, it will still show up until you refresh the page.
Try pasting javascript:alert(document.cookie); in your browser to verify you don't have multiple cookies saved. Clear all cookies for the domain you're working on to make to sure you're starting fresh. Also ini_set(E_ALL); to make sure you're not missing any notices.
Seems to be a server issue. My last domain was pretty relaxed on PHP error handling while the new domain shows every error. I'm using both sites side by side and the old one removes the cookie as it should.
Is there perhaps a timezone issue here? Have you tried setting using something farther in the past, like time() - (3600*24)? PHP's documentation says that the internal implementation for deleting cookies uses a timestamp of one year in the past.
Also, you should be able to use just setcookie('username', false); without passing an expiration timestamp, since that argument is optional. Maybe including it is confusing PHP somehow?
How you use cookies data in your application?
If you read the cookies and check if username is not false or not '', then setting it to false or '' will be sufficient, since your application will ignore the cookies value.
You better put some security in cookies value, to prevent user change it's value. You can take a look of CodeIgniter session library, see how CI protect the cookies value using hash. Unauthorized value change will detected and the cookies will be deleted.
Also, CI do this to kill the cookies:
// Kill the cookie
setcookie(
$this->cookie_name,
addslashes(serialize(array())),
(time() - 31500000),
$this->cookie_path,
$this->cookie_domain,
0
);
You can delete cookies from javascript as well. Check here http://www.php.net/manual/en/function.setcookie.php#96599
A simple and convenient way, is to use this additional functions:
function getCookie($name) {
if (!isset($_COOKIE[$name])) return false;
if ($_COOKIE[$name]=='null') $_COOKIE[$name]=false;
return $_COOKIE[$name];
}
function removeCookie($name) {
unset($_COOKIE[$name]);
setcookie($name, "null");
}
removing a cookie is simple:
removeCookie('MyCookie');
....
echo getCookie('MyCookie');
I had a similar issue.
I found that, for whatever reason, echoing something out of logout.php made it actually delete the cookie:
echo '{}';
setcookie('username', '', time()-3600, '/');
I had the same issue; I log out (and I'm logged out), manually reload the index.php and then I'm logged in again. Then when I log out, I'm properly logged out.
The log out is a simple link (index.php?task=logout). The task removes the user from the session, and "deletes" (set value '' and set expiry in the past) the cookie, but index.php will read the user's auth token from the cookie just after this (or all) task (as with normal operations). Which will reload the user. After the page is loaded the browser will show no cookie for the auth token. So I suspect the cookie gets written after page finish loading.
My simple solution was to not read the cookie if the task was set to logout.
use sessions for authentication, don't use raw cookies
http://www.php.net/manual/en/book.session.php