以下範例提供基於檔案的 session 儲存,類似於 PHP session 的預設儲存處理器 files
。此範例可以輕鬆擴展以涵蓋使用您最喜歡的 PHP 支援的資料庫引擎的資料庫儲存。
請注意,我們使用 OOP 原型與 session_set_save_handler() 並使用函式的參數旗標註冊關閉函式。當註冊物件作為 session 儲存處理器時,通常建議這樣做。
<?php
class MySessionHandler implements SessionHandlerInterface
{
private $savePath;
public function open($savePath, $sessionName): bool
{
$this->savePath = $savePath;
if (!is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}
return true;
}
public function close(): bool
{
return true;
}
#[\ReturnTypeWillChange]
public function read($id)
{
return (string) @file_get_contents("$this->savePath/sess_$id");
}
public function write($id, $data): bool
{
return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
}
public function destroy($id): bool
{
$file = "$this->savePath/sess_$id";
if (file_exists($file)) {
unlink($file);
}
return true;
}
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
{
foreach (glob("$this->savePath/sess_*") as $file) {
if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
unlink($file);
}
}
return true;
}
}
$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();
// proceed to set and retrieve values by key from $_SESSION