php - php中的 session 超时问题

标签 php session-state

我已将 session 超时时间设置为 20 分钟,如下所示。有时 session 超时会在两三分钟内发生。

ini_set('session.gc_maxlifetime',   1200);

ini_set('session.cookie_lifetime',  1200);

ini_set('session.gc_probability',   1);

ini_set('session.gc_divisor',   100);

可能是什么问题?

最佳答案

当用户浏览其他页面时,20 分钟的有效期不会重置this comment 中解释了该问题:

As PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params(), we need to do something in order to change the session expiry time every time the user visits our site. So, here's the problem.

$lifetime=600;
session_set_cookie_params($lifetime);
session_start();

This code doesn't change the lifetime of the session when the user gets back at our site or refreshes the page. The session WILL expire after $lifetime seconds, no matter how many times the user requests the page. So we just overwrite the session cookie as follows:

$lifetime=600;
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);

And now we have the same session cookie with the lifetime set to the proper value.

更好的做法是,将 session.cookie_lifetime 保留为 0,这样当浏览器关闭时 cookie 就会过期。否则,假设关闭浏览器将结束 session 的用户会在 20 分钟超时前重新打开浏览器时感到惊讶。

关于 gc_xxxx 设置的编辑

gc_probability = 1, gc_divisor = 1, gc_maxlifetime = 1200

1/1 表示 PHP 将检查每次 session_start 调用的 session 文件的日期。

gc_probability = 1, gc_divisor = 100, gc_maxlifetime = 1200

1/100 表示 PHP 将随机检查 session 文件的日期,但大约每 100 次 session_start 调用一次。

日期检查本身包括将 session 文件的访问时间与 gc_maxlifetime 进行比较;如果在过去(例如)20 分钟内未访问该文件,它将删除该文件。

话虽如此,如果 cookie 由于超时(或超时为 0 时浏览器关闭)而过期,则 session 会立即过期,因为浏览器会停止发送过期的 session ID cookie;在这种情况下,PHP 会发出一个新的 session ID cookie。与过期 cookie 关联的 session ID 文件被废弃,不再被访问;因此如上所述随时收集垃圾。

最后,您的具体问题可以通过 (i) 查看 session ID cookie 的到期日期 (ii) 并记住在访问/刷新页面时不会更新带有超时的 cookie 来解决。

关于php - php中的 session 超时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15197826/

相关文章:

php - 使用 imagemagick 自定义字体

php - 如果同名变量为空, session 值将被删除

web-applications - 从其他线程关闭 http session

jsf-2 - JSF 登录期间 session 何时创建?

asp.net - 迁移到 Azure 托管以及如何选择 session 状态、数据库和服务器

php - 通过JQuery获取多个按钮的值

php - 缩小大型处理作业

php - 类中的闭包数组

php - 在 PHP $_SESSION 中存储数据不安全吗?

asp.net - MVC - 用户必须在 IIS Recycle 上重新进行身份验证