php - 从数据库中清除过期 session

标签 php mysql session

我目前将 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/

相关文章:

php - 当安全性不受威胁时,php 中可用的最高性能散列算法是什么?

java - 我可以使用户的所有 session 过期吗?

php - 在 MySQL 中复制一条记录

php - 在Wordpress插件开发中处理上传的文件

php - 如何显示每篇文章总评论数

mysql - 如何选择字段具有特定值的所有记录,直到出现具有不同值的记录?

session - JSF 在 shiro 中更改 session 超时

asp.net - 重建后 ASP.NET/IIS 中的 session 为空

php - 如何通过 mysqli 在 PHP 中使用准备好的语句调用 MySQL 存储过程?

mysql - 在 Mysql 中,如何使用性能模式查找哪些查询导致 cpu% 增加了多少?