views:

2390

answers:

1

I am trying to write PHP code to delete all of the user cookies on my domain.

Here is what I got:

<?php
$domain = 'www.example.com';
$deleteExpiration = time() - 60*60*24*365*10; // 10 years ago
foreach (array_keys($_COOKIE) as $cookie) {
    setcookie($cookie, 0, $deleteExpiration, '/', $domain);
}

Running this code on http://www.example.com/delete_cookies.php deletes all cookies that were set on the server, but not cookies that were set in JavaScript.

I verified using the Firefox Cookies dialog that the problematic cookies are indeed from (path=/; domain=www.example.com). Using Live HTTP headers, I can see that the following header is sent:

Set-Cookie: CookieName=0; expires=Fri, 12-Mar-1999 19:36:15 GMT; path=/; domain=www.example.com

So I believe the setcookie command is working as expected. Firefox is just not honoring the request.

One additional thing that I noticed is that if I set a cookie with domain=www.example.com on the server, then it is listed in the Firefox cookie dialog with domain=".www.example.com", but if I set the following cookie using JavaScript code then the leading dot is not added.

What am I doing wrong? How can I delete these cookies?

+3  A: 

I've had a similar issue and it was solved by just not passing the domain.

setcookie($cookie, '', 1, '/');

On a side note from cookie_spec "Setting the path to a higher-level value does not override other more specific path mappings. If there are multiple matches for a given cookie name, but with separate paths, all the matching cookies will be sent." So if you have same name cookies at different path locations you will have to delete each one.

gradbot
It worked! I managed to delete the problematic cookies by omitting the domain parameter. Thanks.
sagi