SessionHandlerInterface クラス

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

はじめに

SessionHandlerInterface は カスタムセッションハンドラを作成する際の最低限のプロトタイプを定義したインターフェイスです。 自作のセッションハンドラを オブジェクト指向型 の起動方法で session_set_save_handler() に渡すために、このインターフェイスを実装することができます。

このクラスのコールバックメソッドは PHP が内部的にコールするものであり、 ユーザーのコードから呼ばれることは想定していないことに注意しましょう。

インターフェイス概要

interface SessionHandlerInterface {
/* メソッド */
public close(): bool
public destroy(string $id): bool
public gc(int $max_lifetime): int|false
public open(string $path, string $name): bool
public read(string $id): string|false
public write(string $id, string $data): bool
}

例1 SessionHandlerInterface の使用例

この例では、ファイルベースのセッションストレージをつくります。これは PHP のデフォルトのセッション保存ハンドラである files と似たものです。この例をさらに拡張すれば、 PHP がサポートするお好みのデータベースを使ってセッションを保存させるようにするのも簡単です。

session_set_save_handler() でオブジェクト指向型のプロトタイプを使っていることと、 シャットダウン関数をその parameter フラグで登録していることに注目しましょう。 オブジェクトをセッション保存ハンドラとして使うときには、この方法をおすすめします。

警告

コードを簡潔にするため、以下の例では入力値の検証を省略しています。 しかし、$id パラメータは パストラバーサル問題のような脆弱性を避けるために、 適切な 検証/無害化 が必須になる値です。 よって、ここで示した例を改変することなく、 本番の実環境で用いないでください

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

// $_SESSION への値の設定や格納されている値の取得を進めます

目次