Cookies
Reading a cookie
The client will send all eligible cookies available along with the request head and PHP will automagically make all sent-in cookies available in $_COOKIE⚑
$color = (string) isset($_COOKIE['color']) ? $_COOKIE['color'] : '#FFFFFF';Setting a cookie
Use setcookie()⚑
setcookie('color', $value, time() + 24*60*60*7);⚠ Remember that the cookie won't immediately become available in $_COOKIE as setcookie() is merely an instruction for the client to create the cookie upon receival of the generated response
Deleting a cookie
Set the cookie with an expiry date set in the past.
setcookie('color', $value, time() - 24*60*60*7);Sessions
Starting/Continuing a session
Use session_start()⚑ to start or continue a previous session. PHP will look for a sent-in PHPSESSID (usually sent in automatically via a cookie) and will continue that session (viz. it will populate $_SESSION⚑ with the previously saved data). If PHPSESSID is empty a new PHPSESSID with empty $_SESSION will be generated.
session_start();ℹ You only need to start the session once for the PHP file. It is recommended to start it at the very top, just beneath the includes/requires.
⚠ All code below won't work if you don't start the session first!
Storing sessiondata
Push an entry onto $_SESSION⚑, like you would manipulate a regular array
$_SESSION['name'] = 'Bramus!';Getting sessiondata
$name = isset($_SESSION['name']) ? $_SESSION['name'] : 'stranger';Removing sessiondata
unset($_SESSION['name']);Stopping a session
foreach ($_SESSION as $key => $value) unset($_SESSION[$key]);
session_destroy();