Summary - Cookies
Build a theme preference (dark/light) app with setcookie, $_COOKIE and expiration.
Summary - Cookies
In this group you learned the four pillars of cookies: create with setcookie(), read with $_COOKIE, set an expiration with time() + N, and delete with a past date.
Combined, they form a simple preference system: the user picks a theme, you store it as a cookie, and on later visits you read it from $_COOKIE.
The last step is a mini app that remembers a dark/light theme preference.
The theme preference app
A theme preference app has two steps: write and read.
Write: when the user picks a theme, set a one-week cookie with setcookie('theme', 'dark', time() + 604800).
Read: on every page load, check isset($_COOKIE['theme']); if defined use the cookie value, otherwise use the 'light' default. The site then remembers the choice for a week.
Exercise Summary - Build the theme preference
Set a one-week theme cookie with setcookie('theme', 'dark', time() + 604800). Then, with if/else, check isset($_COOKIE['theme']): if defined, assign $_COOKIE['theme'] to $theme; otherwise assign 'light'. Finally echo $theme.
Show example solution
Call setcookie('theme', 'dark', time() + 604800), use if(isset($_COOKIE['theme'])) to set $theme from the cookie, else 'light', then echo $theme.
Example solution:
<?php
// Set the theme cookie and read it safely from $_COOKIE
setcookie('theme', 'dark', time() + 604800);
if (isset($_COOKIE['theme'])) {
$theme = $_COOKIE['theme'];
} else {
$theme = 'light';
}
echo $theme . "\n";
Test yourself
-
Match the cookie tools
- setcookie()
- Creates a cookie
- $_COOKIE
- Reads a cookie
- time() + N
- Sets an expiration
- unset($_COOKIE['k'])
- Deletes in this request
-
What is the cookie deletion flow?
- setcookie(name, '', time()-3600) and unset($_COOKIE[name])
- Only rewrite with setcookie(name, 'value')
- Only unset($_COOKIE[name])
- Only session_destroy()
Show answer
setcookie(name, '', time()-3600) and unset($_COOKIE[name]) — Correct. First setcookie with a past date deletes from the browser, then unset clears this request.
-
Set the theme cookie from the config
<?php $cfg = ['name' => 'theme', 'value' => 'dark', 'ttl' => 604800]; ____ echo $cfg['value'];Show answer
<?php $cfg = ['name' => 'theme', 'value' => 'dark', 'ttl' => 604800]; setcookie($cfg['name'], $cfg['value'], time() + $cfg['ttl']); echo $cfg['value'];