默認 Session 存儲在文件系統,分布式部署、高併發、跨服務器共享 Session 時需改用數據庫、Memcached 或 Redis。PHP 提供 session_set_save_handler() 註冊自定義存儲引擎。本文提供**生產級 MySQL Handler**、**Memcached/Redis 簡潔配置**、以及**現代框架集成**方案。
實現 SessionHandlerInterface 七個方法:
interface SessionHandlerInterface {
public function open($savePath, $sessionName): bool;
public function close(): bool;
public function read($sessionId): string|false;
public function write($sessionId, $data): bool;
public function destroy($sessionId): bool;
public function gc($maxLifetime): int|false;
public function create_sid(): string; // PHP 7.1+
}
<?php
namespace App\Session;
use SessionHandlerInterface;
class MySqlSessionHandler implements SessionHandlerInterface
{
private \PDO $pdo;
private string $table;
private int $lifetime;
public function __construct(\PDO $pdo, string $table = 'sessions', int $lifetime = 0)
{
$this->pdo = $pdo;
$this->table = $table;
$this->lifetime = $lifetime ?: (int)ini_get('session.gc_maxlifetime');
$this->createTableIfNotExists();
}
private function createTableIfNotExists(): void
{
$sql = <<table}` (
`id` VARCHAR(255) NOT NULL PRIMARY KEY,
`data` BLOB NOT NULL,
`expires` INT UNSIGNED NOT NULL,
`last_activity` INT UNSIGNED NOT NULL,
INDEX `expires_idx` (`expires`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SQL;
$this->pdo->exec($sql);
}
public function open($savePath, $sessionName): bool { return true; }
public function close(): bool { return true; }
public function read($sessionId): string|false
{
$stmt = $this->pdo->prepare(
"SELECT `data` FROM `{$this->table}` WHERE `id` = ? AND `expires` > ?"
);
$stmt->execute([$sessionId, time()]);
$row = $stmt->fetch(\PDO::FETCH_COLUMN);
return $row !== false ? $row : '';
}
public function write($sessionId, $data): bool
{
$expires = time() + $this->lifetime;
$sql = "INSERT INTO `{$this->table}` (`id`, `data`, `expires`, `last_activity`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE `data` = VALUES(`data`), `expires` = VALUES(`expires`), `last_activity` = VALUES(`last_activity`)";
$stmt = $this->pdo->prepare($sql);
return $stmt->execute([$sessionId, $data, $expires, time()]);
}
public function destroy($sessionId): bool
{
$stmt = $this->pdo->prepare("DELETE FROM `{$this->table}` WHERE `id` = ?");
return $stmt->execute([$sessionId]);
}
public function gc($maxLifetime): int|false
{
$stmt = $this->pdo->prepare("DELETE FROM `{$this->table}` WHERE `expires` < ?");
$stmt->execute([time()]);
return $stmt->rowCount();
}
public function create_sid(): string
{
return bin2hex(random_bytes(32)); // 256-bit 安全 ID
}
}
<?php
// bootstrap.php 或 index.php 最頂部
require 'vendor/autoload.php';
$pdo = new PDO('mysql:host=127.0.0.1;dbname=app;charset=utf8mb4', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$handler = new \App\Session\MySqlSessionHandler($pdo, 'sessions', 1440); // 24分鐘
session_set_save_handler($handler, true); // true = 註冊 shutdown function
session_start();
// 現在正常使用 $_SESSION
$_SESSION['user_id'] = 123;
; php.ini
session.save_handler = user
session.save_path = "mysql:host=127.0.0.1;dbname=app;table=sessions" ; 由自定義類解析
; 但通常不推薦,因為需要自定義類自動加載,易出問題。推薦代碼註冊。
PHP 內置 memcached、redis session handler(需安裝對應擴展)。
<?php
// php.ini 或運行時 ini_set
ini_set('session.save_handler', 'memcached');
ini_set('session.save_path', '127.0.0.1:11211'); // 多台: "10.0.0.1:11211, 10.0.0.2:11211"
// 可選:權重
// ini_set('session.save_path', '10.0.0.1:11211:10, 10.0.0.2:11211:20');
session_start();
$_SESSION['test'] = 'memcached session';
<?php
ini_set('session.save_handler', 'redis');
ini_set('session.save_path', 'tcp://127.0.0.1:6379?auth=yourpass&database=1&prefix=session:');
// 支持參數: auth, database, prefix, timeout, read_timeout, retry_interval
// 集群: "tcp://host1:6379, tcp://host2:6379"
session_start();
// composer require predis/predis
use Predis\Client;
$redis = new Client(['scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379]);
// 手動實現 SessionHandlerInterface 並使用 $redis,或用現成庫:
// composer require norv/session-handler
// 參考: https://github.com/norv/session-handler
**不要手寫**,框架已內置完善支持:
| 框架 | 配置文件 | 驅動設置 |
|---|---|---|
| Laravel | config/session.php | 'driver' => 'database' / 'redis' / 'memcached' / 'array' |
| Symfony | config/packages/framework.yaml | handler_id: session.handler.native / pdo / redis / memcached |
| ThinkPHP 6/8 | config/session.php | 'type' => 'redis' / 'memcache' / 'pdo' / 'file' |
| Yii 2 | config/web.php | 'session' => ['class' => 'yii\web\DbSession' / 'yii\redis\Session'] |
session_id() 設置或 create_sid() 生成 256-bit 隨機字符串,防暴力破解。ini_set('session.cookie_secure', 1); ini_set('session.cookie_httponly', 1); ini_set('session.cookie_samesite', 'Lax');session.gc_probability = 0),由定時任務 (Cron) 定期清理過期數據,避免請求阻塞。session_write_close() 提前釋放鎖。ini_set('session.serialize_handler', 'php_serialize'); (PHP 5.5.4+) 或自定義 Handler 中 json_encode/decode。prefix 避免鍵衝突。session_start() **之後** 註冊 handler → 必須在之前。expires 必須建索引,GC 才快。write() 返回 false 導致 Session 數據不保存 → 檢查 SQL 錯誤、主鍵衝突、權限。session_write_close() 長請求阻塞並發。Session 存儲遷移是架構演進必經之路。理解 SessionHandlerInterface 契約,選擇成熟驅動 (Redis 首選),配合框架配置,即可實現分布式、高可用、安全的 Session 管理。