大阪市中央区 システムソフトウェア開発会社

営業時間:平日09:15〜18:15
MENU

PHP セッションをDBに保存するには2

株式会社クローバーフィールドの経営理念
著者:津路高広
公開日:2024/03/15
最終更新日:2024/03/15
カテゴリー:技術情報
タグ:

津路です。
PHP セッションをDBに保存するにはでは、現象を確認しました。

Windows10+WSL2環境で、https://www.php.net/manual/ja/class.sessionupdatetimestamphandlerinterface.php をみて、
localhost環境で、SessionUpdateTimestampHandlerInterface を実装してみることにしました。

1.public updateTimestamp(string $id, string $data): bool
この関数では、DBに保存しているのだから、return false; としました。
2.public validateId(string $id): bool
常に trueを返すべきかと。。。

テストしてみますと、前回で取り上げました、Warningが消えました。

sessionディレクトリは更新されません。
データベースのsessionテーブルはというと、更新時刻カラムの値がすぐには更新されません。
$_SESSIONに与える値を更新すると、更新されます。
なぜかと、ドキュメントページを見ますと、以下の指摘があります。

When session.lazy_write is enabled, which is the default behaviour, session data will NOT be UPDATED if it remains unchanged, in this way the WRITE method of the session handler will not be called at all.

If your session handler storages session data into files, UpdateTimestamp is used to update the “last modified time” of the session file, if your session handler storages session data into a database, UpdateTimestamp is used to update the table field that storages the last modified time of the session registry.

session.lazy_writeがデフォルトONですので、セッションデータが更新されないと、writeメソッドが呼ばれないと書いてあります。
また、ファイルに保存する場合は、セッションファイルの更新時刻を更新するのにUpdateTimestampが呼ばれ、一方、データベースに保存する場合は、更新時刻テーブルフィールドを更新するのに、UpdateTimestampが呼ばれるとあります。

「この値は、PHP が処理を行うために内部的に返す値であることに注意して下さい。」とあるので、なぜ実装しないとwarningが出るのか、不思議ですが。

    上に戻る