萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP Session 存入 MySQL/Memcached/Redis:自定義 Session Handler 完整實現

默認 Session 存儲在文件系統,分布式部署、高併發、跨服務器共享 Session 時需改用數據庫、Memcached 或 Redis。PHP 提供 session_set_save_handler() 註冊自定義存儲引擎。本文提供**生產級 MySQL Handler**、**Memcached/Redis 簡潔配置**、以及**現代框架集成**方案。

一、自定義 Session Handler 接口 (PHP 7.0+)

實現 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+
}

二、生產級 MySQL Session Handler

<?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
    }
}

三、註冊與使用

1. 早期註冊(入口文件/啟動引導)

<?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;

2. 配置 php.ini (全局生效)

; php.ini
session.save_handler = user
session.save_path = "mysql:host=127.0.0.1;dbname=app;table=sessions" ; 由自定義類解析
; 但通常不推薦,因為需要自定義類自動加載,易出問題。推薦代碼註冊。

四、Memcached / Redis 極簡配置 (無需寫類)

PHP 內置 memcached、redis session handler(需安裝對應擴展)。

Memcached

<?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';

Redis (phpredis 擴展)

<?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();

Redis (Predis 純 PHP 库,無需擴展)

// 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 / Symfony / ThinkPHP)

**不要手寫**,框架已內置完善支持:

框架配置文件驅動設置
Laravelconfig/session.php'driver' => 'database' / 'redis' / 'memcached' / 'array'
Symfonyconfig/packages/framework.yamlhandler_id: session.handler.native / pdo / redis / memcached
ThinkPHP 6/8config/session.php'type' => 'redis' / 'memcache' / 'pdo' / 'file'
Yii 2config/web.php'session' => ['class' => 'yii\web\DbSession' / 'yii\redis\Session']

六、關鍵最佳實踐

  1. Session ID 安全: 使用 session_id() 設置或 create_sid() 生成 256-bit 隨機字符串,防暴力破解。
  2. HTTPS + Secure Cookie: ini_set('session.cookie_secure', 1); ini_set('session.cookie_httponly', 1); ini_set('session.cookie_samesite', 'Lax');
  3. GC 概率: 數據庫存儲建議關閉 PHP 自帶 GC (session.gc_probability = 0),由定時任務 (Cron) 定期清理過期數據,避免請求阻塞。
  4. 鎖競爭: 默認文件 Session 有鎖,數據庫/Redis 也會有行鎖/鍵鎖。長時間請求可 session_write_close() 提前釋放鎖。
  5. 數據序列化: 默認 PHP serialize 格式,跨語言共享 Session 時改用 JSON:ini_set('session.serialize_handler', 'php_serialize'); (PHP 5.5.4+) 或自定義 Handler 中 json_encode/decode。
  6. 前綴隔離: 多應用共享 Redis/Memcached 時,設置 prefix 避免鍵衝突。

七、避坑清單

  • ❌ 在 session_start() **之後** 註冊 handler → 必須在之前。
  • ❌ MySQL 表無索引 → expires 必須建索引,GC 才快。
  • ❌ write() 返回 false 導致 Session 數據不保存 → 檢查 SQL 錯誤、主鍵衝突、權限。
  • ❌ 忘記 session_write_close() 長請求阻塞並發。
  • ❌ 直接信任客戶端 Session ID → 嚴格驗證、綁定 IP/User-Agent(可選)。

Session 存儲遷移是架構演進必經之路。理解 SessionHandlerInterface 契約,選擇成熟驅動 (Redis 首選),配合框架配置,即可實現分布式、高可用、安全的 Session 管理。

copyright © 萬盛學電腦網 all rights reserved