A PHP session stores data on the server and links requests with an identifier, usually carried in a cookie. The browser holds the identifier, not the full $_SESSION array.
Start or resume the session before output, rotate the ID when privileges change, and remove authentication state deliberately during logout.
<?php
session_start();
$_SESSION['completed_lessons'] = ($_SESSION['completed_lessons'] ?? 0) + 1;
echo (string) $_SESSION['completed_lessons'];
The value remains available to later requests that resume the same valid session.
After credentials are verified and before authenticated state is stored, regenerate the session identifier. Production session rotation must account for concurrent requests and unstable networks.
<?php
session_start();
// Run only after the password has been verified.
session_regenerate_id();
$_SESSION['user_id'] = 42;
$_SESSION['authenticated_at'] = time();
Flash data is a value intended for one later request, such as a success message after redirect. Read and remove it together so stale messages do not repeat.
<?php
session_start();
$message = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);
if ($message !== null) {
echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
}
The default file session handler locks a session while a request has it open. A slow request can therefore block another request from the same user. Read or update the required values, then call session_write_close() before long database, file, or network work.
Cookie expiration and server-side record cleanup are separate. Enforce idle and absolute authentication limits in application state, and configure garbage collection for the session handler. Browser cookie lifetime alone is not a security timeout.
0 of 2 checked
Try this next
0 of 2 completed
Explore 500+ free tutorials across 20+ languages and frameworks.