📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Sessions

Sessions

5 min read Quiz at the end
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"
]);
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which function must be called before using sessions?
💡 session_start() must be called before any session operations and before output.
2. How do you delete a session variable?
💡 unset($_SESSION["key"]) removes a specific session variable.
3. How do you completely destroy a session?
💡 Best practice: call session_destroy() AND set $_SESSION = [] to clear data.
4. Why should httponly be set on session cookies?
💡 httponly prevents JavaScript access to cookies, protecting against XSS attacks.
5. What should you call after a successful login?
💡 session_regenerate_id(true) creates a new session ID to prevent session fixation attacks.