0

Per http://php.net/manual/en/function.setcookie.php, they provide the following example to delete a cookie:

setcookie ("TestCookie", "", time() - 3600);

Selected answer to Remove a cookie recommends the following:

setcookie('Hello', null, -1, '/');

Should it be time()-3600, -1, or something else?

On a side note, is a value of null or "" preferred?

Community
  • 1
  • 1
user1032531
  • 22,993
  • 61
  • 191
  • 346
  • 2
    Any time before the current time works. – Barmar Dec 19 '14 at 17:59
  • Value doesn't matter, setting previous date as @Barmar said will remove the cookie. – Rahil Wazir Dec 19 '14 at 18:00
  • it has to be a previous time PER THE CLIENT. if the client's clock is way off, then you'd still be setting a time in THEIR future, e.g. continuing the cookie. Best choice is to set `time = 1`, which 'd be 1970. If a user's clock is that far out, too bad for them. – Marc B Dec 19 '14 at 18:02
  • @Barmar My experience told me the same, but I didn't know whether browsers did so because it was required by the specifications governing browsers, or just because it is the common thing to do. – user1032531 Dec 19 '14 at 18:04
  • Did you try reading the [documentation](http://php.net/manual/en/function.setcookie.php)? _When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser._ – Barmar Dec 19 '14 at 18:09
  • @Barmar Yes, I read the documentation. It is just that I saw many different implementations which presumably were all doing the same thing, and didn't know whether one was better than the other. – user1032531 Dec 19 '14 at 18:11

2 Answers2

0

Try this

if (isset($_COOKIE['TestCookie'])) 
{
    // removing the cookie
    unset($_COOKIE['TestCookie']);

    // resetting the cookie
    setcookie('TestCookie', null, -1, '/');

    return true;
} else {
    return false;
}
ehime
  • 7,617
  • 12
  • 48
  • 107
0

Since cookie expiration time will be checked against clients clock, the best option is:

setcookie('Hello', null, 1, '/');

Then you can make sure it will expire instantly.

Except if the clock is 00:00:00 1970-01-01 :P

  • Why `1` and not `0`? Also, why `null` and not `""`? – user1032531 Dec 19 '14 at 18:08
  • @NelsonGaldemanGraziano It does matter, as 1 and 0 are times, the difference between 0 and 1 is the life of the cookie, aka one second. As well with Null and Empty string, empty string is a nullable value, but is not identical to null: http://php.net/manual/en/language.operators.comparison.php – ehime Dec 19 '14 at 18:24
  • In this context, 1 or 0 it's the same, because it will always compare it with +1000000000 – Nelson Galdeman Graziano Dec 22 '14 at 02:34