Skip to content

PHP Sessions — Complete Guide to Server-Side Session Management

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about PHP Sessions. We cover key concepts, practical examples, and best practices to help you master this topic.

PHP sessions store user-specific data on the server across multiple page requests, identified by a unique session ID stored in a cookie or passed via URL.

What You'll Learn

By the end of this tutorial, you'll start and manage sessions, store and retrieve session data, configure session settings, secure sessions, implement login/logout, and use database session handlers.

Why Sessions Matter

Sessions enable user authentication, shopping carts, and multi-step forms. Unlike cookies, session data stays on the server where it's secure from client-side tampering.

Real-World Use

A banking application uses sessions to track the logged-in user. When the user logs out or is inactive for 15 minutes, the session is destroyed, protecting their account.

Sessions Learning Path

flowchart LR
  A[Cookies] --> B[Sessions]
  B --> C[JSON]
  C --> D[File Handling]
  D --> E[Errors]
  A --> F{You Are Here}
  style F fill:#f90,color:#fff

Starting a Session

<?php
session_start();  // Must be called before any output
$_SESSION["user_id"] = 42;
$_SESSION["username"] = "alice";
$_SESSION["role"] = "admin";
echo "Session ID: " . session_id();

Accessing Session Data

<?php
session_start();
if (isset($_SESSION["user_id"])) {
    echo "Welcome back, " . htmlspecialchars($_SESSION["username"]);
} else {
    echo "Please log in";
}

Destroying Sessions

<?php
session_start();
// Clear session data
$_SESSION = [];
// Delete session cookie
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), "", time() - 3600,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}
// Destroy session
session_destroy();

Session Configuration

<?php
// In php.ini or before session_start()
ini_set("session.gc_maxlifetime", 3600);       // Session lifetime: 1 hour
ini_set("session.cookie_lifetime", 0);          // Until browser closes
ini_set("session.use_strict_mode", 1);          // Reject uninitialized session IDs
ini_set("session.use_only_cookies", 1);         // Don't use URL-based sessions
ini_set("session.cookie_httponly", 1);          // Not accessible via JS
ini_set("session.cookie_secure", 1);            // HTTPS only
ini_set("session.cookie_samesite", "Strict");    // CSRF protection

Flash Messages

<?php
session_start();
// Set flash message
$_SESSION["flash"] = "Profile updated successfully!";
// On next page, display and clear
if (isset($_SESSION["flash"])) {
    echo "<div class='alert'>" . htmlspecialchars($_SESSION["flash"]) . "</div>";
    unset($_SESSION["flash"]);
}

Database Session Handler

<?php
class DatabaseSessionHandler implements SessionHandlerInterface {
    private PDO $db;
    public function __construct(PDO $db) { $this->db = $db; }
    public function open(string $path, string $name): bool { return true; }
    public function close(): bool { return true; }
    public function read(string $id): string {
        $stmt = $this->db->prepare("SELECT data FROM sessions WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetchColumn() ?: "";
    }
    public function write(string $id, string $data): bool {
        $stmt = $this->db->prepare("REPLACE INTO sessions (id, data, updated_at) VALUES (?, ?, NOW())");
        return $stmt->execute([$id, $data]);
    }
    public function destroy(string $id): bool {
        $stmt = $this->db->prepare("DELETE FROM sessions WHERE id = ?");
        return $stmt->execute([$id]);
    }
    public function gc(int $max_lifetime): int {
        $stmt = $this->db->prepare("DELETE FROM sessions WHERE updated_at < DATE_SUB(NOW(), INTERVAL ? SECOND)");
        $stmt->execute([$max_lifetime]);
        return $stmt->rowCount();
    }
}
session_set_save_handler(new DatabaseSessionHandler($pdo), true);
session_start();

Common Mistakes

1. Not Calling session_start() on Every Page

Each page that needs session access must call session_start() before output.

2. Storing Sensitive Data in Session Variables

Session files on disk may be readable by other users. Encrypt sensitive data or store just a reference.

3. Session Fixation

Attackers can set a known session ID. Regenerate session ID after login with session_regenerate_id(true).

4. Not Setting Session Lifetime

Default session lifetime may be too long (24 minutes Garbage Collection). Set appropriate maxlifetime.

5. Output Before session_start()

Any HTML output before session_start() causes headers already sent error. Use output buffering.

Practice Questions

1. What is the difference between cookies and sessions?

Cookies store data on the client (4KB limit, visible). Sessions store data on the server (unlimited, secure).

2. How do you destroy a session in PHP?

Clear $_SESSION array, delete the session cookie, and call session_destroy().

3. Why should you regenerate session ID after login?

To prevent session fixation attacks where an attacker sets a known session ID before the user logs in.

4. What is session.gc_maxlifetime?

The time (in seconds) after which session data is considered garbage and eligible for cleanup.

5. Challenge: Create a login/logout system using sessions.

<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] === "POST" && $_POST["action"] === "login") {
    $_SESSION["user"] = ["id" => 1, "name" => "Alice"];
    session_regenerate_id(true);
}
if ($_SERVER["REQUEST_METHOD"] === "POST" && $_POST["action"] === "logout") {
    $_SESSION = [];
    session_destroy();
}
echo $_SESSION["user"]["name"] ?? "Not logged in";

FAQ

Where are session files stored?

Default: /tmp. Configured by session.save_path in php.ini.

Can sessions work without cookies?

Yes, with session.use_trans_sid, but this passes session ID in URLs (less secure).

What is session fixation?

An attack where the attacker sets a known session ID and tricks the user to authenticate with it.

How do I increase session timeout?

Set session.gc_maxlifetime and session.cookie_lifetime to desired values in seconds.

Can I store objects in sessions?

Yes, but the class definition must be loaded before session_start() for proper unserialization.

Mini Project: Login Tracker

Build a session-based system that tracks user login time and page views.

<?php
session_start();
if (!isset($_SESSION["started"])) {
    $_SESSION["started"] = time();
    $_SESSION["views"] = 1;
} else {
    $_SESSION["views"]++;
}
$elapsed = time() - $_SESSION["started"];
echo "Session active for $elapsed seconds (" . $_SESSION["views"] . " page views)";

What's Next

PHP JSON PHP File Handling PHP Errors

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro