Delete cookie from browser? - php

Is there any way of instructing a web browser to completely delete one's cookie set with PHP?
I do not want to expiry it or wait for the browser to be closed.
With delete I mean to actually not have it listed inside the cookie's list anymore.

Try something like this to delete all cookies:
foreach ($_COOKIE as $name => $value) {
setcookie($name, '', 1);
}
The value 1 is the expire value and it represents one second after the begin of the Unix time epoch. So it’s always already expired.

You cannot force the browser to delete the file associated with any cookie, because you can't guarantee there's actually such a file - the contract between browser and web server regarding cookies is that the data will be presented at eligible requests.
You state that you "don't want to wait for the cookie to expire", but cookie expiration is the correct method for indicating that the data is no longer needed and should not be presented on future requests, which in most cases does translate to the browser removing the file.
To delete a cookie, therefore, set its expiration time into the past. In PHP, this is done with setcookie().

Yes. Use setcookie() and set the expiration date for the cookie you wish to delete to a time in the past. The user's browser should automatically remove it as a result.

'Seems that deleting a cookie is more difficult than it looks.
setcookie($name, '', 1);
Won't do the trick. The '' is empty and setcookie can ignore the whole instruction.
Also setting the time to the past sometimes allows the cookie to retain the value whose expire time is newer than 1.
I am dealing with this right now. I don't know where it comes from, but it's there.
I've resorted to
setcookie($name, '0', 9000000000);
This ensures the cookie is set to a value that resolves to false and that it is newer than any previous value.
If anyone has any insight into this behavior please tell.
I suspect the difficulty lies in the fact that the domain and path values for setcookie are guaranteed to be the same from execution to execution when the values are not specified.
And I am aware such a cookie will not expire until 2038 or so.
Alternately, if the newest expiration date of the cookie is known, it need be set only 1 second after.

I think that you have to use combined approach:
set expiration way back in the past (as suggested by Chacha102)
use JavaScriptto delete entries from document.cookie DOM object (as suggested by andres descalzo)
There are 2 good reasons for going with mixed approach:
JavaScript can be disabled in the browser
not all cookies are visible in document.cookie Some modern browsers are supporting httponly flag for cookies. PHP has support for httponly cookies, see http://www.php.net/setcookie

I wrote this plugin for me and works correctly.
(function($) {
$.cookieAllDelete = function(doc)
{
var cookie_date = new Date();
var cookies = null;
cookies = doc.cookie.split(';');
cookie_date.setTime(cookie_date.getTime() - 1);
for(var i=0; i < cookies.length; i++)
{
var cookie_name = cookies[i].split('=')[0];
try {
if (cookie_name.length > 0)
doc.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
} catch(ex) {}
}
}
})(jQuery);
jQuery.cookieAllDelete(document);

Related

Browser remembering cookies even if not supposed to

I have built my logging in and out system but it seems to not work correctly in some browsers like chrome and firefox. The problem is that the browsers remember cookies even if they're meant to expire at session end.
Does anyone have a solution for that?
I'd just like to note that creating another cookie to monitor if it's supposed to remember or not is not a valid solution, there must be a more professional way.
Thank you in advance!
EDIT: I apologize I got confused. I'm not unsetting the cookie at all, the browser is supposed to destroy it when it's closed but it doesn't. That's the problem
Set the expiration date to the past
// set the expiration date to one hour ago
setcookie ("cookie", "", time() - 3600);
See this example from php manuals.
EDIT:
To delete cookies when the browser or the tab is closed, you can use javascript onunload.
<script>
window.onunload=function()
{
document.cookie = 'cookie =; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
</script>
It will set the cookie expiration date to the past, on page unload.
To delete a cookie you need to set a negative time.
setcookie('cookie', '', time() - 3600);
Like PHP Doc says:
If set to 0, or omitted, the cookie will expire at the end of the
session (when the browser closes)
This is the idea of PHP but some Browsers don't do that. Just set a negative Time like
setcookie("cookie", "", time() - 10);
and it works.

Php cookie not setting

Alright I'm totally baffled.
Here's my code:
if ($password == $correct_password[0] && !isset($_COOKIE['user'])) {
setcookie("user", $email, time() + 3600);
var_dump(isset($_COOKIE['user']));
echo "!";
}
So it's doing the var_dumps, meaning that the setcookie should called. But the line right after it (checking if it's set) says it's not set!
If anyone could point out the problem it'd be greatly appreciated. Thanks
$_COOKIE is populated/loaded when the script first starts up, and then is NOT updated by PHP again for the life of the script. Setting a cookie via setcookie will only show up in $_COOKIE on the NEXT execution of the script.
This applies to all of the superglobals, except $_SESSION. They're populated/initalized at script startup and then PHP does not ever touch them again. $_SESSION is populated when you call session_start() (or sessions are set to auto start), which may be done multiple times within a script's lifetime.
PHP is a server-side language.
That means that it can generate whatever it wants and will then pass it to the client.
And that's it.
There is no back and forward on a single request.
1º you instruct the page 'A' to set a cookie
2º client recieves page 'A' and sets the cookie
3º client asks for page 'B' (sending the cookie)
4º server can identify the cookie (only on page 'B')
Page here is used as simple way of understanding a server call.
You can request the same page twice for the purpose.
Still didn't find a solid valid answer, but after endless hours of testing it seems like something with the time. If I set the expiration date too close to the real time, maybe it doesn't register or something. It seemed to work when I set the time further, but I'm taking a break before heavy testing again.
Thanks
When you use setcookie() it will save its value the next time that the HTML is loaded. If you want to see the vardump with the value you just assigned you will need to use $_COOKIE['cookie_name'] = $value;

Set cookie and update cookie problem - Php

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.

Using cookies with php

I'm just trying to set and use a cookie but I can't seem to store anything.
On login, I use:
setcookie("username", $user);
But, when I use Firefox and the Web Developer plugin Cookies -> View Cookie Information There is no username cookie.
Also, when I try to access the value from a subsequent page using
$_COOKIE["username"]
It is returning null/empty
var_dump(setcookie("username", $user));
RESULT: bool(true)
and
var_dump($_COOKIE)
RESULT: specific cookie does not exist (others are there)
I have done some more testing...
The cookie exists after login (first page) but disappears when I go to another (2nd page) and is lost for good...
Are there any headers that must be present or not present?
http://php.net/manual/en/function.setcookie.php
Try setting the $expire parameter to some point in the future. I believe it defaults to 0, which is in the distant past.
Make sure that you are setting the domain parameter correctly in case the URL is changing after you go to another page after login. You can read more about the domain parameter on http://php.net/manual/en/function.setcookie.php
The cookie is probably expired because $expire defaults to 0 seconds since the Unix epoch. (docs)
Try
setcookie("username", $user, time() + 1200);
which expires 20 minutes after set (based on the client's time).
Use var_dump() on setcookie(..) to see what is returned. Also might do the same to $_COOKIE to see if the key is set.
Thanks everyone for the feedback... Aditya lead me to further analyse the cookie and I discovered that the path was the issue...
The login path was /admin/ and then I was redirecting back to the root...
Thanks all for your help and feedback!

Cookie won't unset

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

Categories