Coding/Learn/php/php cookies and sessions
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnCookies, Sessions & State Management
12 / 20 0%
Lesson 12 of 20
9 mins read

Cookies, Sessions & State Management

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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().

PointCore Rules to Remember

Point star
Must Precede Output: session_start() and setcookie() must be called before ANY HTML or echo output is sent.
Point star
Always Set HttpOnly: Always flag sensitive cookies with httponly => true to prevent stolen sessions via XSS.
Point star
Server-Side Privacy: Session data is stored securely on the server; clients only hold an opaque session ID token.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Always regenerate session IDs (session_regenerate_id(true)) immediately after authenticating a user password.

Live Interactive Example

Hit Run Code to see it live
State Simulation with In-Memory Session Array
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: Simulated session data retrieval and demonstrated the flash message pattern with unset().

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Simulate Cart Item Addition in Session

  • PointInitialize an array $session = ["cart" => []].
  • PointAppend "Mechanical Keyboard" to $session["cart"].
  • PointAppend "USB-C Hub" to $session["cart"].
  • PointPrint "Cart Items: [count] -> [item1, item2]".
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates