Deleting cookies
Learn to delete a cookie by setting it with a past expiration.
Deleting with a past expiration
You do not delete a cookie with unset(); $_COOKIE only holds the copy for the current request. The real deletion happens when the browser drops the cookie.
To do this, call setcookie() again with the same name, an empty value and a past expiration: setcookie('user', '', time() - 3600).
The browser sees the past date and drops the cookie at once. On the next request $_COOKIE['user'] no longer arrives.
Also clear $_COOKIE in this request
setcookie() deletes the cookie, but the change takes effect on the next request from the browser. In the current request $_COOKIE['user'] still holds the old value.
So the deletion flow is two steps: first send the delete message to the browser with setcookie('user', '', time() - 3600), then clear this request's copy with unset($_COOKIE['user']).
This way the page behaves as if the cookie is already gone in this very load.
Exercise Delete the 'user' cookie
Call setcookie() with name 'user', empty value '', expiration time() - 3600. Then call unset($_COOKIE['user']). Finally echo gone.
Show example solution
Call setcookie('user', '', time() - 3600), clear with unset($_COOKIE['user']), then echo "gone".
Example solution:
<?php
// Delete the 'user' cookie with a past expiration and clear $_COOKIE
setcookie('user', '', time() - 3600);
unset($_COOKIE['user']);
echo "gone\n";
Test yourself
-
Which expires deletes a cookie?
- time() + 3600
- time() - 3600
- 0
- null
Show answer
time() - 3600 — Correct. A past expiration (time() - 3600) tells the browser to drop the cookie.
-
Delete the cookie with a past date
<?php $cfg = ['name' => 'user']; setcookie($cfg['name'], '', ____); echo 'deleted';Show answer
<?php $cfg = ['name' => 'user']; setcookie($cfg['name'], '', time() - 3600); echo 'deleted'; -
Match the deletion steps
- setcookie(name, '', time()-3600)
- Deletes from browser
- unset($_COOKIE['name'])
- Clears this request
- time() + 3600
- Extends the lifetime
- setcookie(name, 'value')
- Creates a new cookie