我目前将 session 存储在我的mysql数据库中,但是我看到很多 session 的到期日期已到。现在我没有运行任何其他类型的脚本来收集过期的 session 但是我读到了有关垃圾收集的内容,但垃圾收集一旦过期就处理大量过期 session 的可能性较小。
I am looking forward for a script or alternative solution which automatically deletes expired sessions?
最佳答案
你必须实现你的 session 处理程序类,它的 gc 函数可以删除旧的 session 数据:
function gc($lifetime) {
$db = new PDO("mysql:host=myhost;dbname=mydb", "myuser", "mypassword");
$sql = "DELETE FROM session WHERE session_lastaccesstime < DATE_SUB(NOW(), INTERVAL " . $lifetime . " SECOND)";
$db->query($sql);
}
Garbage collection is performed on a random basis by PHP. The probability that garbage collection is invoked is decided through the php.ini directives session.gc_probability and session.gc_divisor. If the probability is set to 1 and the divisor is set to 100 for example, the garbage collector has a 1% chance of being run on each request (1/100).
您需要将 gc 设置为处理程序:
session_set_save_handler(array($sessionHandler,"open"),
array($sessionHandler,"close"),
array($sessionHandler,"read"),
array($sessionHandler,"write"),
array($sessionHandler,"destroy"),
array($sessionHandler,"gc"));
查看有关如何使用它的更多信息:
http://php.net/manual/en/function.session-set-save-handler.php
关于php - 从数据库中清除过期 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35274654/