What I'm wanting to do is for the remember me checkbox. I have it set up to where if there is a cookie set for the username then it checks the checkbox. What I'm wanting to do is if there was a cookie but the user decides to uncheck it just in case someone else wants to access their account from the same computer then it'll delete the cookie I"m not sure how to accomplish this. Here's what I have so far.
if (isset($_POST['remember'])) {
// Sets an expiration time for the cookie
$my_expiration = time()+60*60*24*100;
// Sets the cookie for the username
setcookie("username", $username, $my_exiration, "/");
} else {
setcookie ("username", "", time() - 3600);
}
This will work if you add the path ("/") to the second setcookie() call. Since you are omitting that, the browser is treating the cookie as a different one than the previously-set cookie, and will therefore not delete it:
setcookie ("username", "", time() - 3600, "/");
(At least I assume that's what's going wrong. You didn't actually ask a question, you just sort of threw code up there and said "I'm doing this" without indicating if anything isn't working as you expect.)
Set it to null
setcookie("username", null, 0, "/");
Both setting and deleting must have path
setcookie("ST",$_COOKIE['ST'],time()+1000,'/'); //for creation
setcookie('ST',NULL,-1,'/'); //for deletion
I played with this until get it done.
Hope it useful.
Related
I have created a logout.php page to let the user sign out from the website and redirects them to the sign in page.
however what ever i do, the cookies are not getting deleted, so when the user gets redirected to the singin page the latter examines the cookies and then find it, therefore logs the user in.
Below is the code of logout.php:
<?php
unset($login);
if (isset($_COOKIE['xxx'])){
setcookie('xxx', false, time() - 3600,"/");
}
if (isset($_COOKIE['yyy'])){
setcookie('yyy', false, time() - 3600,"/");
}
header("Location: singin.php");
die();
?>
Please note that this php page is in subfolder protected by password and the html link redirects to a php file that require() the logout.php file.
use php unset() to delete your cookie as, you can get the complete details here delete the cookie
if (isset($_COOKIE['xxx'])){
unset($_COOKIE['xxx']);
}
if (isset($_COOKIE['yyy'])){
unset($_COOKIE['yyy']);
}
or, set value as null and a negative time for your cookie as
setcookie('xxx', null, -1, '/');
setcookie('yyy', null, -1, '/');
or, set value as empty and a past time for your cookie as
setcookie("xxx", "", time()-3600);
setcookie("yyy", "", time()-3600);
I have found finally the reason behind the issue.
it's because I have put session_cache_limiter('public'); in my code, so which I presume prevents the client to set the cookie to an expiry date.
I have done that because I don't want the client to ask the user each time they hit back to resubmit the form.
It seems that it's not the correct practice, I'll post another question for that.
Thanks all for the help.
I can't figure out why I can't remove a cookie or it's value:
I have simple log in script, when user enters correct login details, this is
setcookie('logged', $admin['username'], time()+60*60*24*365);
Also, session_start() is present on all pages.
When I want to log off a user, the following happens:
if($page=='logoff') {
setcookie('logged', "", time() - 3600);
unset($_COOKIE['logged']); // tried also this
session_destroy();
$_SESSION=null;
header("Location: index.php"); // if this is removed, the code below acts like there's no $_COOKIE['logged'] or it's empty (until refresh)
}
Once it gets redirected to index.php the $_COOKIE['logged'] is back with the old value, like something would set it again (nothing does for sure, I even removed the one and only login cookie set line)
I couldn't find a solution in similar questions. Tested in chrome and IE.
You can't "unset" a cookie. "Expire" it by setting it to a value in the past:
<?php
// set the expiration date to one hour ago
setcookie("logged", "", time() - 3600);
?>
http://www.w3schools.com/php/php_cookies.asp
I want to set a cookie if Username is entered and also want the previous cookie to get deleted. I am able to unset the previous cookie but new cookie is not working for me. It showing blank.
if(!empty($User_Name))
{
unset($_COOKIE['username']);
setcookie('username', $User_Name, time()+31536000);
echo $_COOKIE['username']; // blank
}
Any help would be nice.
In my opinion there is no need to unset the cookie. Because, when you set the cookie it will override the existing cookie ( if it exists ) or create a new one ( if it doesn't exist )
From the PHP Docs..
Cookies will not become visible until the next loading of a page that
the cookie should be visible for. To test if a cookie was successfully
set, check for the cookie on a next loading page before the cookie
expires.
Found that if the path is empty it applies only to the current path, if you specify "/" applies to all paths.
so / did the trick.
setcookie('username', $User_Name, time() + (86400 * 7), "/");
In an attempt to get more familiar with cookies I've decided to set up a simple cookie management system to have more control of the information that I can store and retrieve from a user.
The idea is to set a cookie if it does not exist, and update a cookie if it already exists on the user.
Once the cookie is set, it will also be stored in a database that will keep track on when the session started and when it was last accessed.
Creating a cookie worked well at first. But suddenly it stopped working and wouldn't set anything at all. This is the current code of the createSession() function:
function createSession() {
// check to see if cookie exists
if(isset($_COOKIE["test"])) {
// update time
$expire = time()+81400;
setcookie("test","$cookiekey",$expire,"/",false,0);
} else {
// assign unique cookie id
list($msec,$sec)=explode(" ",microtime());
$cookiekey = preg_replace("/./","",($msec+$sec));
// set time
$expire = time()+81400;
// set cookie
setcookie("test","$cookiekey",$expire,"/",false,0);
// assign the unqiue id to $_COOKIE[]
$_COOKIE["test"]=$cookiekey;
unset($cookiekey);unset($msec);unset($sec);unset($expire);
}
}
Is my approach heading in the right direction or have I done something way wrong?
Doing $_COOKIE["test"] = something; doesn't make a "test" cookie. You need to use setcookie again.
I don't know why you'd want to do that though. Why not just check for $_COOKIE["name"] (the cookie that you are making).
Cookies are only available once another request was done. So don’t modify $_COOKIE on your own.
Furthermore, when in your case the cookie exists (i.e. $_COOKIE['test'] is set) you call setcookie again with $cookiekey as its value. But $cookiekey is not defined at that moment so the cookie will be overwritten with an empty string. I guess you want to use $_COOKIE['test'] instead:
if (isset($_COOKIE["test"])) {
// update time
$expire = time()+81400;
setcookie("test", $_COOKIE["test"], $expire, "/", false, 0);
}
You could also save yourself all that pain by using PHP's built in session management (examples here) to handle all of this cookie stuff for you.
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