SessionHandler::gc
Cleanup old sessions
SessionHandler::gc() is a function for garbage collection, it is a built-in function for PHP. Its purpose is to delete expired session data.
usage:
bool SessionHandler::gc(int $maxlifetime): bool
parameter:
Return value:
Example:
class MySessionHandler extends SessionHandler { public function gc($maxlifetime) { // 进行垃圾回收操作,删除过期的会话数据// 在这里可以根据需要自定义垃圾回收的逻辑// 例如,可以删除一周前的会话数据$expiredTime = time() - $maxlifetime; $query = "DELETE FROM sessions WHERE last_accessed < $expiredTime"; // 执行删除操作的代码// ... return true; // 垃圾回收成功} } // 设置自定义的会话处理器$handler = new MySessionHandler(); session_set_save_handler($handler, true); // 启动会话session_start(); // 执行其他操作... // 会话结束时,PHP会自动调用gc()函数进行垃圾回收
In this example, we created a custom session processor class called MySessionHandler
and override gc()
method. In gc()
method, we use SQL statements to delete expired session data a week ago. Then, we set the custom session processor to the processor of the current session through session_set_save_handler()
function. Finally, at the end of the session, PHP will automatically call the gc()
function for garbage collection operations.