PHP Session Management
In this page:
Session Security Checks
Session hijacking happens when an attacker steals a valid session ID and impersonates the user; regenerating the session ID with session_regenerate_id() right after login invalidates any ID an attacker may already have captured.
Example: Session Security Checks
<?php
session_start();
session_regenerate_id(true);
echo "Session ID regenerated after login";
?>
Login to try C/C++/Java/PHP code in the editor
Setting Session Timeout Limits
A simple timeout pattern stores a last-activity timestamp in $_SESSION and checks it on every page load, forcing a logout if too much time has passed -- protecting accounts left open on shared or public computers.
Example: Setting Session Timeout Limits
<?php
session_start();
$timeout = 1800;
$_SESSION['last_activity'] = time() - 2000;
if (time() - $_SESSION['last_activity'] > $timeout) {
echo "Session expired -- logging out";
} else {
$_SESSION['last_activity'] = time();
}
?>
Login to try C/C++/Java/PHP code in the editor
Custom Session Configuration
Before calling session_start(), you can configure cookie lifetime, path, and security flags with session_set_cookie_params(), giving you control over how long a session cookie survives and where it's valid.
Example: Custom Session Configuration
<?php
session_set_cookie_params(3600, '/', '', true, true);
session_start();
echo "Session cookie configured before starting";
?>
Login to try C/C++/Java/PHP code in the editor
Session Status and States
session_status() tells you whether sessions are disabled, inactive, or already active, which is useful for guarding against calling session_start() twice or checking session state before performing sensitive actions.
Example: Session Status and States
<?php
echo session_status() === PHP_SESSION_NONE ? "No session yet\n" : "Session active\n";
session_start();
echo session_status() === PHP_SESSION_ACTIVE ? "Now active" : "Still inactive";
?>
Login to try C/C++/Java/PHP code in the editor
Session Name and ID
session_name() and session_id() let you inspect or override the identifiers PHP uses under the hood, which matters when running multiple independent apps on the same domain that shouldn't share session data.
Example: Session Name and ID
<?php
session_start();
echo session_name() . ": " . session_id();
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: