1

A "browser" session cookie gets deleted when the browser closes. When setting a "browser" session cookie in JavaScript, no expiry date is included.

document.cookie= "MyCookieName = MyValue; path=/";

I would like to delete a "browser" session cookie in php. I have tried this:

setcookie('MyCookieName','', time() - 3600,'/'); 

Unfortunately, the cookie is not getting deleted.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Cymro
  • 1,201
  • 1
  • 11
  • 29

1 Answers1

0

First off, I don't think it makes any difference how the cookie was created (JS or PHP).

You can't force the browser to delete the cookie file. You can, however, delete the contents of the cookie and expire it. Which is exactly what you're doing with your code above. I would probably tweak it slightly:

setcookie('MyCookieName', '', 1, '/'); // no need to calculate one hour ago.

Assuming the cookie had some value, you can check to see if your code took effect:

if ($_COOKIE["MyCookieName"] == '') {
  echo 'cookie was deleted';
}

The file still won't get deleted until the user closes their browser though.

One more thing to check if the above doesn't work is the cookie path (the fourth param in setcookie(). It's possible that the cookie is being set only, for example, for /blog. You should be able to deduce this by inspecting the cookie with Safari webkit developer tools or something similar.

Adam Balsam
  • 785
  • 9
  • 15