web php
Sessions
Sessions are commonly used for login identity, flash messages, CSRF tokens, form progress, and small pieces of short-lived web state. They are not a replacement for database records or long-term domain data.
Starting and using a session
<?php
declare(strict_types=1);
session_start();
$_SESSION['basket_count'] = ($_SESSION['basket_count'] ?? 0) + 1;
echo 'Basket items: ' . $_SESSION['basket_count'] . PHP_EOL;
// Output on the first request:
// Basket items: 1
session_start() must run before output because it may send or read the session cookie. After it runs, $_SESSION behaves like an array for the current user's session.
What belongs in a session
Good session values are small and temporary:
- authenticated user ID
- CSRF token
- flash messages
- short form progress
- last visited page for redirect after login
Avoid storing large objects, entire user records, shopping catalogue data, or permission decisions that should be recalculated from trusted data. Store an ID and load fresh data when needed.
Login state
After successful login, regenerate the session ID before storing the user ID.
<?php
declare(strict_types=1);
$userId = 42;
session_start();
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
echo 'Logged in user: ' . $_SESSION['user_id'] . PHP_EOL;
// Prints:
// Logged in user: 42
Regenerating the session ID helps prevent session fixation, where an attacker tries to make a user log in with a known session ID.
Flash Messages
A flash message should normally be read once and then removed.
<?php
declare(strict_types=1);
$_SESSION = ['flash_success' => 'Profile updated.'];
$message = $_SESSION['flash_success'] ?? null;
unset($_SESSION['flash_success']);
echo $message . PHP_EOL;
echo isset($_SESSION['flash_success']) ? 'still stored' : 'removed';
echo PHP_EOL;
// Prints:
// Profile updated.
// removed
Frameworks usually provide flash helpers, but the underlying idea is simple: session storage carries a message across one redirect.
Session Locking
PHP's default file-backed sessions lock a session while a request is using it. Two requests from the same browser session can block one another if the first request performs slow work before releasing the lock.
When a request no longer needs to change session data, close it early:
<?php
declare(strict_types=1);
session_start();
$userId = $_SESSION['user_id'] ?? null;
session_write_close();
echo $userId === null ? 'guest' : 'user ' . $userId;
echo PHP_EOL;
Do not keep a session lock open while generating a large report or waiting for an external API unless the request genuinely needs it.
Logging Out
Logout should clear authentication state, invalidate the server-side session data, and expire the browser's session cookie using the same cookie scope. Frameworks usually provide a tested logout flow; use it instead of removing only $_SESSION['user_id'].
What you should be able to do
After this lesson, you should be able to explain how sessions use a cookie plus server-side storage, start and close a session safely, use flash messages, choose sensible session data, regenerate the session ID when authentication state changes, and describe a complete logout flow.
Practice
Task: Store Login State In A Session
Create a PHP example or checklist for storing login state after successful authentication.
Requirements
- Start the session before reading or writing
$_SESSION. - Regenerate the session ID before storing the user ID.
- Store a small user identifier, not a full user object.
- Include one example of temporary session data such as a flash message.
- Add a short note explaining why sessions are not long-term storage.
Check your work
The answer should show session state as short-lived web state tied to a browser session.
Show solution
<?php
declare(strict_types=1);
$userId = 42;
session_start();
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
$_SESSION['flash_success'] = 'Signed in successfully.';
echo 'User: ' . $_SESSION['user_id'] . PHP_EOL;
echo $_SESSION['flash_success'] . PHP_EOL;
// Prints:
// User: 42
// Signed in successfully.
The session stores a small identifier and temporary message, not the full user record. Sessions are short-lived web state; durable facts such as users, orders, permissions, and audit history belong in persistent storage.