Sessions store user data across multiple pages, like keeping a user logged in. Start with session_start() and use $_SESSION to store and read data. Call session_regenerate_id(true) after login to prevent session fixation attacks.
PHP Sessions
Sessions store user data across multiple page requests.
// Start session (must be before any output)
session_start();
// Store data
$_SESSION["user_id"] = 42;
$_SESSION["username"] = "alice";
$_SESSION["role"] = "admin";
// Read data
$user = $_SESSION["username"] ?? "Guest";
// Check if exists
if (isset($_SESSION["user_id"])) {
echo "Logged in";
}
// Remove specific key
unset($_SESSION["cart"]);
// Destroy entire session (logout)
session_destroy();
$_SESSION = [];
// Session config
session_set_cookie_params([
"lifetime" => 3600, // 1 hour
"secure" => true,
"httponly" => true,
"samesite" => "Strict"
]);