How to Unset/Remove a Cookie Immediately with PHP (Even for the Current Request, Without Having to Refresh the Page)

How to Unset/Remove a Cookie Immediately with PHP (Even for the Current Request, Without Having to Refresh the Page)

Setting cookies is generally done using setcookie(), that’s a known fact. However, unsetting them generally is a bit trickier, since the cookie remains available throughout the current request, if requested via the global variable:

$_COOKIE['the_cookie_name']

The cookie is fully removed/expired on the next page refresh.

The function below will avoid this behavior. It will still remove the cookie on the next page request, but it will also make it unavailable during the current request too, essentially “expiring”/”removing” it immediately.

function removeCookie($cookieName){ unset($_COOKIE[$cookieName]); setcookie($cookieName, '', time() - 3600, '/'); } To remove e.g. a cookie named “last_username”, you would call:

removeCookie("last_username"); Image credit to @Ginny