CakeFest 2024: The Official CakePHP Conference

SessionHandlerInterface::write

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

SessionHandlerInterface::writeセッションのデータを書き込む

説明

public SessionHandlerInterface::write(string $id, string $data): bool

セッションのデータをセッションストレージに書き込みます。 session_write_close() からコールされ、 session_register_shutdown() が失敗したときや通常のシャットダウン時にもコールされます。 SessionHandlerInterface::close() がこの関数の直後にコールされることに注意しましょう。

PHP は、セッションの保存と終了の準備ができたときにこのメソッドをコールします。 スーパーグローバル $_SESSION のセッションデータをエンコードして 文字列にシリアライズし、セッション ID とともにこのメソッドに渡して格納させます。 シリアライズの方式は session.serialize_handler で設定します。

このメソッドが PHP からコールされるのは、通常は出力バッファが閉じた後であることに注意しましょう。ただし、 明示的に session_write_close() をコールした場合は別です。

パラメータ

id

セッション id。

data

エンコードされたセッションデータ。 これは、PHP がスーパーグローバル $_SESSION の内容を内部的にシリアライズした結果の文字列で、それがこのパラメータに渡されます。 セッションのシリアライズには通常とは別の方式を使っていることに注意しましょう。

戻り値

返り値 (通常は、true が成功そして false が失敗を表します)。この値は PHP で内部的に処理されるものであることに注意しましょう。

add a note

User Contributed Notes 3 notes

up
3
jotremb at hotmail dot com
7 years ago
It is important to note that if returning FALSE from this method, PHP will in turn output the following warning:

Warning: Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0.

This could cause minor inconveniences, however if the session should not be written as per design, then returning TRUE after handling (and not writing) the session will avoid further issues.

All in all, better return TRUE at all times except in cases of hard errors.
up
2
barkoczi dot roland at aercode dot com
8 years ago
Note: this function won't be called in case $session_data is unchanged. In order to call this function every time when session is about closing, add $_SESSION["timestamp"] = time();
up
1
Aeric Poon
4 years ago
Warning: session_write_close(): Session callback expects true/false return value in Unknown on line 0

I have returned TRUE in write() but the warning still persist. Then I also return TRUE in close() and the warning is gone.
To Top