Sessions & Cookies Management
HTTP is stateless. PHP uses cookies and sessions to store user data across multiple page loads.
1 Cookies (Client) vs. Sessions (Server)
State management in PHP divides data storage between client and server:
- Cookies: Data stored directly on the client's browser (e.g. tracking identifiers). Set using the `setcookie()` function. They are sent to the server automatically with every page request.
- Sessions: Secure data stored on the web server (e.g. login credentials). Initiated using the **`session_start()`** function at the very top of the script. Values are stored inside the `$_SESSION` superglobal array.
2 Session Code
Let's look at an example initializing sessions and setting cookies:
PHP — Sessions & Cookies
▶ Run Code
<?php
// Start the session (must be the first line of the script)
session_start();
// Store data in session
$_SESSION['user_id'] = 405;
$_SESSION['role'] = "Administrator";
echo "Session Started! User ID: " . $_SESSION['user_id'] . "\n";
// Set a cookie (expires in 1 hour)
setcookie("theme", "dark", time() + 3600, "/");
echo "Theme Cookie initialized.\n";
?>
3 Code Challenge
Challenge: Write a script that checks if a session variable exists using the `isset()` function. If it does, print its value; otherwise, initialize it with a default value.