How can a custom session handler be implemented in PHP for better session management?

Custom session handlers can be implemented in PHP to provide better session management by allowing developers to store session data in a custom storage mechanism, such as a database or external service. This can help improve security, scalability, and flexibility of session management in PHP applications.

<?php
// Custom session handler class
class CustomSessionHandler implements SessionHandlerInterface {
    private $db;

    public function open($savePath, $sessionName) {
        // Initialize database connection
        $this->db = new PDO('mysql:host=localhost;dbname=sessions', 'username', 'password');
        return true;
    }

    public function close() {
        // Close database connection
        $this->db = null;
        return true;
    }

    public function read($sessionId) {
        // Read session data from database
        $stmt = $this->db->prepare("SELECT data FROM sessions WHERE id = :id");
        $stmt->execute(['id' => $sessionId]);
        $data = $stmt->fetchColumn();
        return $data;
    }

    public function write($sessionId, $data) {
        // Write session data to database
        $stmt = $this->db->prepare("REPLACE INTO sessions (id, data) VALUES (:id, :data)");
        $stmt->execute(['id' => $sessionId, 'data' => $data]);
        return true;
    }

    public function destroy($sessionId) {
        // Delete session data from database
        $stmt = $this->db->prepare("DELETE FROM sessions WHERE id = :id");
        $stmt->execute(['id' => $sessionId]);
        return true;
    }

    public function gc($maxLifetime) {
        // Garbage collection to remove expired sessions from database
        $stmt = $this->db->prepare("DELETE FROM sessions WHERE TIMESTAMP(created_at) < NOW() - INTERVAL :lifetime SECOND");
        $stmt->execute(['lifetime' => $maxLifetime]);
        return true;
    }
}

// Set custom session handler
$handler = new CustomSessionHandler();
session_set_save_handler($handler, true);

// Start the session
session_start();