0

Say I have a cookie FOO. The method I am using to clear the cookie currently is

if (isset($_COOKIE["FOO"])) {
    unset($_COOKIE["FOO"];
    setcookie("FOO", "", time() - 3600, "/"); // Essentially "clear" the cookie
}

I unthinkingly copy-pasted from here. I realize the if statement is not necessary (I could simply unset and setcookie without testing), but does the if make it more efficient if FOO is not set? In other words, if the cookie is not set, is it more efficient to "clear" it anyway, or test for if it exists and do nothing if it does not exist.

  • You dont NEED too, but it saves bothering with extra code if it doesn't exist in the first place. The 'efficiency' is in the micro nano milliseconds... so, don't worry about it... unless you are always setting/clearing about 1000 cookies with every page. – IncredibleHat Jan 30 '18 at 19:32
  • Thanks, this is what I figured, but I didn't know if there was a best practice that I was unaware of. –  Feb 07 '18 at 14:37
  • I'm unaware of any Best Practice™ :) I always do check in the case of 'killing' a cookie no longer in use. Like I changed a cookie to a different name, and I want to help purge people's browsers of dead cookies. Then I would check if it exists before clearing... that way its not setting/clearing a dead cookie for every visit by everyone who possibly never had it. Normal cookies in play I don't bother checking if they exist. Like logout... I always purge them on logout, no isset checks, just purge. – IncredibleHat Feb 07 '18 at 15:20

0 Answers0