PHP中的会话超时问题

4

我已经设置了20分钟的会话超时时间,如下所示。有时会话超时在两到三分钟内发生。

ini_set('session.gc_maxlifetime',   1200);

ini_set('session.cookie_lifetime',  1200);

ini_set('session.gc_probability',   1);

ini_set('session.gc_divisor',   100);

可能存在什么问题?

你的脚本可能在代码的其他地方覆盖了这些设置吗? - Peon
1
ini_get()函数返回什么? - Mihai Iorga
session.cookie_lifetime 是以分钟为单位而非秒钟定义的值。 - s.lenders
@s.lenders session.cookie-lifetime - Class
可能是PHP会话过快超时的重复问题。 - Álvaro González
1个回答

1
20分钟的过期时间不会在用户浏览其他页面时重置。该问题在此评论中有解释:

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会过期。否则,用户可能会认为关闭浏览器会结束他们的会话,但在20分钟超时之前重新打开浏览器时,他们会感到惊讶。
关于gc_xxxx设置的编辑
gc_probability = 1, gc_divisor = 1, gc_maxlifetime = 1200 1/1表示PHP将在每个session_start调用时检查会话文件的日期。
gc_probability = 1, gc_divisor = 100, gc_maxlifetime = 1200 1/100意味着PHP将随机检查会话文件的日期,但大约每100个session_start调用一次。
日期检查本身包括比较会话文件的访问时间和gc_maxlifetime;如果文件在过去(例如)20分钟内没有被访问,则会删除该文件。
如果cookie因超时而过期(或在超时为0时关闭浏览器),则会立即过期,因为浏览器停止发送过期的会话ID cookie;此时PHP会发出新的会话ID cookie。与过期cookie关联的会话ID文件将被放弃,不再被访问;因此可以像上面描述的那样随时进行垃圾回收。
最后,您可以通过查看会话ID cookie的到期日期来解决您的特定问题,并记住当页面被访问/刷新时,具有超时时间的cookie不会被更新。

那怎么回答问题呢? - Madara's Ghost
1
是的,它没有,我现在已经添加了引用。 - Salman A
Gumbo的回答应该解释了会话和GC是如何工作的。此外,您还需要检查正在交换的cookie。看起来在1分钟后过期的会话可能是19分钟前启动的会话。您正在通过ini_set设置session.cookie_lifetime,这与使用session_set_cookie_params相同。 - Salman A
谢谢你的回答,它很有帮助。我还有一个疑问。你提到,对于下面的情况,GC将大约在100次调用中发生一次。 gc_probability = 1,gc_divisor = 100,gc_maxlifetime = 1200;我访问页面一次,20分钟后刷新。实际上,这是我的页面的第二个调用,现在GC会删除我的文件吗?因为GC将在100个调用中发生一次。1/100的概率是针对每个会话还是全局的?这意味着GC将在同一会话的100个调用或来自所有会话(不同用户的会话)的调用中的一个调用中发生? - user1536854
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/25524/discussion-between-user1536854-and-salman-a - user1536854
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接