I spent two full days trying to figure out why a cookie I created with setcookie()
refused to be deleted. Spoiler: it wasn’t a bug in PHP, it was me missing one tiny detail.
Here’s the story—and the fix.
The Code That Didn’t Work
I created a cookie like this:
setcookie('param', 'data', time() + 3600);
And then tried to delete it like this:
setcookie('param', '', time() - 3600);
But the cookie just wouldn’t go away. I cleared my browser, inspected dev tools, double-checked everything. Still there.
I even tried encoding the value with md5()
and base64_encode()
—but that wasn’t the issue at all.
The Real Issue: Path Matters!
After much frustration and some Stack Overflow rabbit holes, I learned that the fourth parameter of setcookie()
—the path—is crucial.
If the path isn’t explicitly set, the cookie might not get deleted properly. Why? Because the browser might have stored the cookie with a default path like /current-directory
, and when you try to delete it without matching that path, it ignores your command.
The Correct Way:
setcookie('param', 'data', time() + 3600, '/');
setcookie('param', '', time() - 3600, '/'); // Properly deletes the cookie
Setting the path to '/'
ensures that the cookie is accessible (and removable) site-wide.
Another Gotcha: Cookies Aren’t Available Immediately
Right after you call setcookie()
, the cookie won’t appear in $_COOKIE
. Why? Because the cookie hasn’t been sent to the browser and returned yet—it’ll only exist on the next request.
This won’t work:
setcookie('param', 'data', time() + 3600, '/');
echo $_COOKIE['param']; // Won’t print anything yet
Workaround for Testing:
setcookie('param', 'data', time() + 3600, '/');
if (!isset($_COOKIE['param'])) {
echo "<script>window.location.reload();</script>";
} else {
echo $_COOKIE['param'];
}
Obviously, don’t use this in production—this is just a quick hack to test that your cookie is set correctly.
Final Thoughts
Here’s what I learned (so you don’t waste two days like I did):
- ✅ Always set the path when using
setcookie()
—especially when deleting. - ✅ Cookies are only available in
$_COOKIE
after the next page load. - ❌ Don’t assume calling
setcookie()
immediately updates$_COOKIE
.
Summary:
// To set:
setcookie('param', 'data', time() + 3600, '/');
// To delete:
setcookie('param', '', time() - 3600, '/');
This tiny slash /
in the path can save you hours of debugging.
Happy cookie handling!