Cookie expiration
Learn to set a cookie's lifetime by passing an expiration to setcookie().
Expiration and time()
By default a cookie lives until the browser closes. Give it an expiration and it lives longer. The third argument to setcookie() is a Unix timestamp.
time() returns the current timestamp in seconds (since 1 Jan 1970). Add seconds to compute a future date: time() + 3600 is one hour ahead.
Example: setcookie('lang', 'en', time() + 86400) keeps the cookie for 24 hours.
Persistent cookies
A cookie with a third argument is persistent: it survives on disk until the expiration, even if the browser is closed. This is ideal for user preferences (language, theme).
Without an expiration the cookie is a session cookie: deleted when the browser window closes. This suits temporary state.
A past expiration makes the browser delete the cookie immediately; we use this for deletion.
Exercise Create a one-week cookie
Call setcookie() with name 'prefs', value 'dark', and expiration time() + 604800 (one week). Then echo set.
Show example solution
Call setcookie('prefs', 'dark', time() + 604800), then echo "set".
Example solution:
<?php
// Create the 'prefs' cookie with a 1-week expiration
setcookie('prefs', 'dark', time() + 604800);
echo "set\n";
Test yourself
-
Add a one-hour expiration
<?php $cfg = ['name' => 'token', 'value' => 'abc']; setcookie($cfg['name'], $cfg['value'], ____); echo 'set';Show answer
<?php $cfg = ['name' => 'token', 'value' => 'abc']; setcookie($cfg['name'], $cfg['value'], time() + 3600); echo 'set'; -
What does time() return?
- Seconds since 1 January 1970
- Current date in YYYY-MM-DD format
- The cookie's expiration
- A duration in microseconds
Show answer
Seconds since 1 January 1970 — Correct. time() returns the Unix timestamp in seconds.
-
Match the duration expressions
- time() + 3600
- 1 hour
- time() + 86400
- 1 day
- time() + 604800
- 1 week
- time() + 31536000
- 1 year