Python Cookies, Sessions & State Management
HTTP is stateless by default. PHP bridges this with client-side Cookies and server-side Sessions. Master setcookie() with security flags (HttpOnly, Secure, SameSite), session_start(), the $_SESSION array, and session fixation defense.
"A cookie is like a coat-check claim ticket handed to the visitor. A session is the actual private locker in the back room: the visitor presents the claim ticket (session ID), and PHP opens their corresponding locker ($_SESSION)."
Deep Dive: How It Works
Cookies (Client-Side): setcookie($name, $value, $options) writes a Set-Cookie HTTP header.
Cookie Security Options: httponly (blocks JS access/XSS), secure (HTTPS only), samesite => "Strict"|"Lax" (prevents CSRF).
Sessions (Server-Side): session_start() reads the session cookie, restores the session file, and populates $_SESSION.
Session Regeneration: session_regenerate_id(true) rotates the session ID upon user login to prevent session fixation.
Syntax Blueprint
<?php session_start(); $_SESSION["user_id"] = 42; $_SESSION["role"] = "admin"; // Destroy session session_destroy();
Initialize session with session_start(), read/write $_SESSION variables, and destroy with session_destroy().
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Calling session_start() after echoing output: "Headers already sent".Why it happens: HTTP cookies and session headers can only be sent before the response body begins.
How to fix: Always invoke session_start() at the very top of your entry point script.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Simulate Cart Item Addition in Session
Initialize an array $session = ["cart" => []].
Append "Mechanical Keyboard" to $session["cart"].
Append "USB-C Hub" to $session["cart"].
Print "Cart Items: [count] -> [item1, item2]".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.