CREATE TABLE `sessions` (
`session_id` CHAR(32) NOT NULL PRIMARY KEY,
`user_id` INT UNSIGNED NOT NULL DEFAULT 0,
`data` TEXT NOT NULL,
`last_activity` INT UNSIGNED NOT NULL DEFAULT 0,
`ip_address` VARCHAR(45) DEFAULT '',
`user_agent` TEXT DEFAULT '',
INDEX `idx_last_activity` (`last_activity`),
INDEX `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
<?php
class MySQLSessionHandler implements SessionHandlerInterface {
private PDO $pdo;
private int $lifetime;
public function __construct(PDO $pdo, int $lifetime = 3600) {
$this->pdo = $pdo;
$this->lifetime = $lifetime;
}
// 打開會話(返回 true 表示成功)
public function open(string $savePath, string $sessionName): bool {
return true; // PDO 連接已在構造函數建立
}
// 關閉會話
public function close(): bool {
return true;
}
// 讀取會話數據
public function read(string $sessionId): string|false {
$stmt = $this->pdo->prepare('SELECT `data` FROM `sessions` WHERE `session_id` = ? AND `last_activity` > ? LIMIT 1');
$stmt->execute([$sessionId, time() - $this->lifetime]);
$row = $stmt->fetch(PDO::FETCH_COLUMN);
return $row !== false ? $row : '';
}
// 寫入會話數據
public function write(string $sessionId, string $data): bool {
$userId = 0;
// 嘗試從序列化數據中提取 user_id(可選)
if (preg_match('/user_id\|i:(\d+);/', $data, $m)) {
$userId = (int)$m[1];
}
$stmt = $this->pdo->prepare(
'INSERT INTO `sessions` (`session_id`, `user_id`, `data`, `last_activity`) VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE `user_id` = VALUES(`user_id`), `data` = VALUES(`data`), `last_activity` = VALUES(`last_activity`)'
);
return $stmt->execute([$sessionId, $userId, $data, time()]);
}
// 銷毀會話
public function destroy(string $sessionId): bool {
$stmt = $this->pdo->prepare('DELETE FROM `sessions` WHERE `session_id` = ?');
return $stmt->execute([$sessionId]);
}
// 垃圾回收(刪除過期)
public function gc(int $maxLifetime): int|false {
$stmt = $this->pdo->prepare('DELETE FROM `sessions` WHERE `last_activity` < ?');
$stmt->execute([time() - $maxLifetime]);
return $stmt->rowCount();
}
}
<?php
require 'db.php'; // 返回 $pdo 實例
$handler = new MySQLSessionHandler($pdo, 3600); // 1 小時過期
session_set_save_handler($handler, true); // true = 註冊關閉函數
session_start();
// 現在 $_SESSION 讀寫自動走 MySQL
$_SESSION['user_id'] = 123;
$_SESSION['name'] = 'Alice';
| 指令 | 推薦值 | 說明 |
|---|---|---|
session.save_handler | user | 使用用戶自定義處理器 |
session.save_path | /tmp (無效,由處理器決定) | 文件存儲時的路徑;自定義處理器忽略 |
session.name | PHPSESSID | Cookie 名稱 |
session.auto_start | 0 | 禁止自動啟動(類定義需先載入) |
session.gc_probability | 1 | GC 概率分子 |
session.gc_divisor | 1000 | GC 概率分母(1/1000 請求觸發) |
session.gc_maxlifetime | 1440 | 最大生存秒數(GC 判斷標準) |
session.use_cookies | 1 | 使用 Cookie 傳遞 ID |
session.use_only_cookies | 1 | 禁止 URL 傳 ID(防會話固定) |
session.cookie_httponly | 1 | JS 不可讀 |
session.cookie_secure | 1 | 僅 HTTPS(生產必開) |
session.cookie_samesite | Lax | CSRF 防護 |
MySQL 寫入有鎖開銷,高併發下建議使用 **Redis**(原子操作、亞毫秒延遲、內建 TTL 自動過期):
class RedisSessionHandler implements SessionHandlerInterface {
private Redis $redis;
private string $prefix = 'sess:';
public function __construct(Redis $redis) { $this->redis = $redis; }
public function read($id) { return $this->redis->get($this->prefix . $id) ?: ''; }
public function write($id, $data) { return $this->redis->setex($this->prefix . $id, 3600, $data); }
public function destroy($id) { return $this->redis->del($this->prefix . $id); }
public function gc($maxLifetime) { return 0; } // Redis 自動過期,無需 GC
public function open($p, $n) { return true; }
public function close() { return true; }
}