Skip to content

Instantly share code, notes, and snippets.

@quantum5
Created July 30, 2025 09:10
Show Gist options
  • Save quantum5/3b124db7b48389e743a3836ca4481deb to your computer and use it in GitHub Desktop.
Save quantum5/3b124db7b48389e743a3836ca4481deb to your computer and use it in GitHub Desktop.
Implementation of PDO-based sessions in PHP (MySQL/MariaDB-only for now)
<?php
/* Schema
CREATE TABLE php_sessions (
id VARCHAR(32) NOT NULL PRIMARY KEY,
access BIGINT NOT NULL,
data BLOB NOT NULL
);
*/
class PDOBackedSession implements SessionHandlerInterface {
public function __construct($dsn, $user = null, $pass = null, $options = []) {
$this->dsn = $dsn;
$this->user = $user;
$this->pass = $pass;
$this->options = array_merge([
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
], $options);
}
public function register() {
session_set_save_handler($this, true);
}
public function open($path, $name) {
try {
$this->pdo = new PDO($this->dsn, $this->user, $this->pass, $this->options);
return true;
} catch (PDOException $e) {
return false;
}
}
public function close() {
$this->pdo = null;
return true;
}
public function read($sid) {
$stmt = $this->pdo->prepare('SELECT data FROM php_sessions WHERE id = ?');
$stmt->execute([$sid]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result ? $result['data'] : '';
}
public function write($sid, $data) {
$stmt = $this->pdo->prepare('REPLACE INTO php_sessions VALUES (?, ?, ?)');
$stmt->execute([$sid, time(), $data]);
return true;
}
public function destroy($sid) {
$stmt = $this->pdo->prepare('DELETE FROM php_sessions WHERE id = ?');
$stmt->execute([$sid]);
return true;
}
public function gc($lifetime) {
$stmt = $this->pdo->prepare('DELETE FROM php_sessions WHERE access < ?');
$stmt->execute([time() - $lifetime]);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment