W3docs

Where are $_SESSION variables stored?

In PHP, $_SESSION variables are typically stored on the server in a file or a database.

In PHP, $_SESSION variables are typically stored on the server in a file or a database. When using the default session handler, PHP stores session data in files on the server in a specific directory. The location of this directory is determined by the session.save_path setting in php.ini. By default, it is typically /tmp on Unix-like systems, though it varies by distribution and often requires explicit configuration in production.

Alternatively, it can be stored in a database by configuring session handlers, like SQLite, MySQL, or Memcached.

To store in a database, you would need to create a table to hold the session data and implement a custom session handler. Modern PHP recommends using the SessionHandler class or SessionHandlerInterface instead of raw callbacks with session_set_save_handler(). For example:

class DbSessionHandler implements SessionHandlerInterface {
    private PDO $pdo;
    public function __construct(PDO $pdo) { $this->pdo = $pdo; }
    public function open(string $path, string $name): bool { return true; }
    public function close(): bool { return true; }
    public function read(string $id): string|false { /* fetch from DB */ return ''; }
    public function write(string $id, string $data): bool { /* save to DB */ return true; }
    public function destroy(string $id): bool { /* delete from DB */ return true; }
    public function gc(int $max_lifetime): int|false { /* cleanup */ return 0; }
}

$handler = new DbSessionHandler($pdo);
session_set_save_handler($handler, true);
session_start();