PHP Sessions: Managing State
PHP Session Variables
A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the session information is stored on the server, with only a session ID cookie sent to the client.
Key Actions:
session_start(): Initializes or resumes a session. Must be called at the very top before any HTML tags.$_SESSION: Associative array holding session data.session_destroy(): Deletes all session data.
Sessions are vital for tracking logins and shopping carts. Because session IDs can be intercepted, developers should regenerate session IDs upon login using session_regenerate_id() to prevent session fixation attacks.
PHP sessions are cleaned up periodically by a garbage collector, which deletes old session files on the server based on configuration limits.
Session ID Regeneration
Regenerating the session ID destroys the old temporary session file and shifts data to a new ID, protecting logins from session hijacking.
php
<?php
session_start();
session_regenerate_id(true);
echo "Session regenerated safely!\n";
?>
php
<?php
session_start();
$_SESSION["userid"] = 1002;
$_SESSION["role"] = "admin";
echo "Session started. User ID: " . $_SESSION["userid"] . "\n";
echo "User Role: " . $_SESSION["role"] . "\n";
?>