<?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.
Related
I have a script that logs out the user (logout.php) and it works perfectly fine in FF and IE, but in Chrome the cookie is still available even after the browser has been closed.
I have tested with this bit of code:
logout.php
session_start();
$_SESSION['un'] = '';
$_SESSION['pw'] = '';
unset($_SESSION['un']);
unset($_SESSION['pw']);
setcookie("spf", "", time()-3600);
session_destroy();
echo "Cookie: ".$_COOKIE['spf']."<br />";
echo "Session: ".$_SESSION['un'];
In Chrome it will still echo out with content for spf despite everything. What am I doing wrong?
Edit:
In FF my testpage echoes this:
Cookie:
Session:
(e.g. blank both).
In Chrome it says this:
Cookie: {\"un\":\"test3333\",\"pw\":\"593c114983263124656dd6bb922b7bd8\"}
Session:
(e.g. the cookie has content and the session is blank).
You can try:
$_SESSION=array(); // assign an empty array to the session
OR
session_unset(); // unset $_SESSION variable for the run-time, frees all session variables currently registered.
INFO
AND THEN :
session_destroy(); // destroy session data in storage
NOTE:
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. To use the session variables again, session_start() has to be called.
In order to kill the session altogether with session_destroy(), like to log the user out, the session id must also be unset. 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.
TAKEN FROM:
INFO
UPDATE:
Then i think you need this, note that spf is the name of the cookie
setcookie ("spf", "", time() - 3600);
if it is an array change the name to spf[one] ex:
setcookie ("spf[un]", "", time() - 3600);
take a look HERE
Set a date in the past and it will do the trick, also don't forget to add a path so you delete the good one.
setcookie('your_cookie', '', time()-3600,'/');
Previously i was creating additional cookie "rememberme" with unique hash, that was stored in the database, mapped to the user id.
If user had such cookie - website tried to find it's value in database, and if it was found session was setting up.
Later, developing new project i thought that it is maybe not very secure to generate this unique hash by myself, and keeping two cookies (native "PHPSESSID" + my "rememberme") for one operation (user identification) is overkill.
Maybe there is a way to setup not global session lifetime, but to setup it individually for different user sessions... or maybe it is better to keep user sessions in the database, mapped to the userid?
UPDATE 1
I thought if it is so hard to make "remember me" button, we can go another way - to make "Not my computer button". Idea is to set default cookie_lifetime for a week in php.ini (for example), and if user checkes this checkbox - we will set cookie_lifetime into zero using session_set_cookie_params function.
So, 1st question is - will session_set_cookie_params affect other users cookies (in documentation it is said, that session_set_cookie_params options will have effect until php process will be executing)
2d question is that if session_set_cookie_params is not affecting global settings, will session regeneration affect users, that don't want to keep a long-life cookie?
UPDATE 2: [Question 1 answer]
Just tested session_set_cookie_params function.
I wrote a script, that sets session cookie lifetime into zero using session_set_cookie_params and then executing for 30 seconds:
if ($_GET['test']) {
session_set_cookie_params (0);
while (true) {
sleep(1);
}
}
session_start();
So, in first browser i just started this script with ?test=1 parameter, just after that (while this script was executing) i started this script without parameters in the second browser. The answer is no - second browser's cookie was not affected. It had lifetime, that was specified in php.ini
UPDATE 3: [Question 2 answer]
Then, i've tried to check if regeneration affects session cookie lifetime, that was set by session_set_cookie_params.
Yes, it affects. If i set session cookie with customized lifetime, that was set by session_set_cookie_params, and then call session_regenerate_id(), cookie will have lifetime, set in php.ini
But, if we set session_set_cookie_params (0) before calling session_regenerate_id(), our cookie will have correct lifetime.
So, that's it! That was easy! 8)
Thank you, ladies and gentlemen!
If you want to do this only using sessions you can do the following if the user wants to be remembered:
if((isset($_POST['remember_me']) && $_POST['remember_me']) || ($_COOKIE['remember_me']) && $_COOKIE['remember_me'])) {
// store these cookies in an other directory to make sure they don't
// get deleted by the garbage collector when starting a "non-remeber-me"-session
$remember_me_dir = ini_get('session.save_path') . DS . "remember_me_sessions";
// create the directory if it doesn't exist
if (!is_dir($remember_me_dir)) {
mkdir($remember_me_dir);
}
// set the php.ini-directive (temporarily)
ini_set('session.save_path', $remember_me_dir);
// define lifetime of the cookie on client side
$expire_cookie = 60 * 60 * 24 * 30; // in seconds
session_set_cookie_params($expire_cookie);
// lifetime of the cookie on server side
// session file gets deleted after this timespan
// add a few seconds to make sure the browser deletes
// the cookie first.
$garbage_in = $expire_cookie + 600; // in seconds
// set the php-ini directive for the garbage collector of the session files.
ini_set('session.gc_maxlifetime', $garbage_in);
// send an additional cookie to keep track of the users
// which checked the 'remember_me' checkbox
setcookie('remember_me', 1, time() + $expire_cookie);
}
// now we are ready to start the session
// For all the users which didn't choose to check the 'remember_me' box
// the default settings in php.ini are used.
session_start();
Here you can read more about the session related php.ini-directives
As it was so hard to make "remember me" checkbox functionality, i came to another way, using only one cookie.
PREPARATION
1) I've prepared a form with three inputs:
"login" input [type=text]: user's login
"password" input [type=password]: user's password
"not my computer" input [type=checkbox]: that will tell us to use session cookie with lifetime = 0 (cookie must be deleted when browser will be closed)
2) I've set session.cookie_lifetime = 100500 to keep long-life cookies by default.
COOKIE SETUP
So, after user submits the form, we check - if he has selected to use short sessions - we call session_set_cookie_params(0) before setting session cookie to him (before actually using session_start()).
COOKIE REGENERATION
Then, when we need to regenerate session cookie, we can also do this easily with session_regenerate_id() function.
But we need to remember, that this function will re-set session cookie lifetime from php.ini by default.
So, we need also to call session_set_cookie_params() before regenerating a cookie.
BTW, You can store custom session cookie lifetime in $_SESSION.
It will look like this:
// Form handling, session setup
if ($_POST['not-my-computer']) {
session_set_cookie_params(0);
session_start();
$_SESSION['expires'] = 0;
}
// Session regeneration
if (isset($_SESSION['expires'])) {
session_set_cookie_params(0);
session_regenerate_id();
}
Details for this answer (and more deep explanations) you can find in the question text (while i was testing, i added answers/tests results there)
I'm having trouble setting cookies on the same page. I used cookies on my site and it works fine, I tend to set make the php in separate file. Now, I'm setting a cookie on the same page but it doesn't seem to work.
$expire = time()+5;
setcookie("rb_vote", 1, $expire);
then check if it is set
if(isset($_COOKIE["rb_vote"])) {
echo "IS SET";}
else {
echo "IS NOT SET"; }
It always says is not set. I tried doing this in page load but still doesn't work.
See the manual on setcookie() (emphasis mine):
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST
Here is a workaround suggestion. It's imperfect because it can't guarantee the cookie actually gets set, but might do in your case.
I've just encountered this issue in Vanilla Forum. On the first page load, before a session has been established, a session cookie is created, but then every time the application wants to access the session variables (to add to them) it looks for the current session ID in $_COOKIE, which is not set until the next page load.
My workaround is to set the $_COOKIE element manually when the cookie is created.
// Create a cookie to identify the session.
// This line already exists. $Name is the cookie name.
// $SessionID is a random md5 ID that has just been generated.
setcookie($Name, $SessionID, $Expire, $Path, $Domain);
// Set the cookie for the remainder of the page. This is a workaround.
if (!isset($_COOKIE[$Name])) $_COOKIE[$Name] = $SessionID;
I've raised this as a fault with Vanilla (https://github.com/vanillaforums/Garden/issues/1568), as this workaround feels like a bit of a hack, but it certainly gets around the problem for now.
PHP5.3 Vanilla Forum Version 2.0.18.4
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
I'm using PHP5 here. I have made a login system that check's the username and password against the records in the database. I want to use sessions to store the logged value. For example, when I reach the zone where I "log in" the user succesfully:
if($errors = 0) {
$_SESSION['logged'] = "1";
}
The problem is that I want the $_SESSION['logged'] to stay active for let's say 5 minutes so when I do a if($_SESSION['logged'] == "1") after this time to return false. Also, I would like to delete this session after the user closes the browser. Basically, I want a session configuration so that the user can safely leave his desk and when him or somebody presses refresh after 10 minutes or enters again after the browser has been closed, the session to be already removed, and the access to be restricted.
Can anybody help? Thanks.
Use session_set_cookie_params() to change the lifetime of the session cookie. Note that by default, it is set to 0 which means that the cookie is set until the user exits the browser. You can do this in the following way:
/* Set to 0 if you want the session
cookie to be set until the user closes
the browser. Use time() + seconds
otherwise. */
session_set_cookie_params(0);
session_start();
Then check for the last activity time, updated each time someone visits a page.
if(($_SESSION['lastActivity'] + 300) < time()) {
// timeout, destroy the session.
session_destroy();
unset($_SESSION);
die('Timeout!');
} else {
$_SESSION['lastActivity'] = time();
}
Instead of setting it to one, why don't you set $_SESSION['logged_time'] = time(); and then check the time against time() in your application?
If you'd like to actually expire the entire session, the exact specifics can change depending on your session handler, but for the default session handler (and any other well behaved session handler) you'll want to check out http://us3.php.net/manual/en/session.configuration.php
You can change the configuration setting session.cookie_lifetime, e.g. in php.ini or a .htaccess file:
session.cookie_lifetime specifies the
lifetime of the cookie in seconds
which is sent to the browser. The
value 0 means "until the browser is
closed." Defaults to 0.
This means (I think) that you can't have both expiry based on a timeout and expiry when the browser is closed. So maybe the best bet is to keep the default and set your own timer in $_SESSION as others have suggested, thus rendering this answer pointless.
Sessions stay alive aslong as the user stays on your site. You will have to use cookies to set a specific timeout.