PHP 8.5.0 Released!

session_gc

(PHP 7 >= 7.1.0, PHP 8)

session_gcセッションデータのガベージコレクションを実行する

説明

session_gc(): int|false

デフォルトで PHP は、 session.gc_probability の設定をを使用して、 各リクエストごとに確率的にセッションガベージコレクタを実行します。 この方法には以下に示すいくつかの制限があります:

  • トラフィックが少ないサイトのセッションデータは、望んだ期間内に削除されないことがあります
  • トラフィックの多いサイトでは、GC が頻繁に行われる可能性があり、余計な処理が行われる可能性があります
  • ガベージコレクションはユーザーのリクエストに基づいて行われるため、ユーザーが遅延を感じる可能性があります

本番環境のシステムでは、 確率ベースのガベージコレクションを session.gc_probability の値を 0 にすることで無効にし、 定期的にガベージコレクタを明示的に実行させることをおすすめします。 たとえば UNIX 系のシステムでは session_gc() をコールするスクリプトを "cron" で実行する方法が挙げられます。

注意: コマンドライン経由で実行する PHP スクリプトから session_gc() を呼び出す場合、 session.save_path については、 Web からのリクエスト時のものと同じ値を設定し、 PHP スクリプトはセッションファイルに対するアクセス権と削除権限が必須です。 権限については、スクリプトを実行するユーザー、 および systemd の PrivateTmp= オプションなどの コンテナやサンドボックス機能の影響を受ける可能性があります。

パラメータ

この関数にはパラメータはありません。

戻り値

session_gc() は、 成功時には削除されたセッションデータの数を返します。 失敗した場合に false を返します

注意: 古いセーブハンドラは、 削除されたセッションデータの数を返さず、成功/失敗フラグのみを返します。 この場合、実際に削除されたデータにかかわらず、 削除されたセッションデータの数は 1 になります。

例1 cron のようなタスクマネージャでの session_gc() の例

<?php
// 注 : このスクリプトは、Web サーバープロセスと同じユーザーで実行される必要があります。
// セッションデータストレージアクセスを初期化するには、アクティブセッションが必要です。
session_start();

// 直ちに GC を実行します
session_gc();

// session_start() によって作成されたセッション ID をクリーンアップします
session_destroy();
?>

例2 ユーザーがアクセス可能なスクリプトでの session_gc() の例

<?php
// 注 : session_gc() は、タスクマネージャスクリプトで使用することをお勧めしますが、次のように使用できます。

// 最後の GC 時間チェックに使用
$gc_time = '/tmp/php_session_last_gc';
$gc_period = 1800;

session_start();
// GC 期限が経過したときにのみ GC を実行します。
// つまり、リクエストのたびに session_gc() をコールすることはリソースの無駄です。
if (file_exists($gc_time)) {
if (
filemtime($gc_time) < time() - $gc_period) {
session_gc();
touch($gc_time);
}
} else {
touch($gc_time);
}
?>

参考

add a note

User Contributed Notes 2 notes

up
1
i dot carvallo at gmail dot com
11 months ago
Do not use:

if (session_gc() == false)
OR
if (!session_gc())

to evaluate if the garbage collector was triggered successfully since it also returns how many sessions it deleted, which can be 0 (and that evaluates to false with loose operators).

Sounds dumb, but it's a pitfall i fell into and it generated some confusion. Instead, use strict operator "===":

if (session_gc() === false)
up
0
ridaelkouri at gmail dot com
1 year ago
The session.gc() function does not seem to work alone. it deletes the data on the server but the data remains on the browser in the form of the cookie. the following code deletes the session files on the server but not on the browser. 

ini_set('session.gc_maxlifetime', 10);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);

// Start the session
session_start();
$_SESSION['test'] = 'temporary data';

session_write_close();

// Wait for 15 seconds to ensure the session expires
sleep(15);

// Manually start the session again to trigger session handling
session_start();

session_gc();

// Check if the session data is still available
if (isset($_SESSION['test'])) {
    echo "Session is still active.";
} else {
    echo "Session expired and file deleted.";
}

but this code delete the session files on the server and also deletes the cookie as well as making the super global empty:

session_start();
$_SESSION['test'] = 'temporary data';

session_write_close();

// Wait for 15 seconds to ensure the session expires
sleep(15);

session_start();

// Manually trigger garbage collection
setcookie(session_name(), '', time() - 10);
$_SESSION = [];
session_gc();

// Check if the session data is still available
if (isset($_SESSION['test'])) {
    echo "Session is still active.";
} else {
    echo "Session expired and file deleted.";
}
To Top