Session timeout issue in php

有些话、适合烂在心里 提交于 2019-12-22 08:26:22

问题


I have set session timeout time for 20 Minutes as below.Sometime the session timeout is happening in two or three minutes.

ini_set('session.gc_maxlifetime',   1200);

ini_set('session.cookie_lifetime',  1200);

ini_set('session.gc_probability',   1);

ini_set('session.gc_divisor',   100);

What could be the issue?


回答1:


The 20 minute expiration does not reset when the user browses other pages. The problem is explained in 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.

Better, leave the session.cookie_lifetime to 0 so that the cookie expires when the browser is closed. Otherwise, users who assume that closing the browser will end their session will be surprised when they re-open their browser before the 20 minute timeout.

Edit regarding gc_xxxx settings

gc_probability = 1, gc_divisor = 1, gc_maxlifetime = 1200

1/1 implies PHP will check the date of session files for every session_start call.

gc_probability = 1, gc_divisor = 100, gc_maxlifetime = 1200

1/100 means PHP will check the date of session files randomly but approximately once per 100 session_start calls.

The date check itself consist of comparing session file's accessed time with gc_maxlifetime; it deletes the file if wasn't accessed in the past (e.g.) 20 minutes.

Having said that, if the cookie expires because of timeout (or closing of browser when timeout was 0) the session expires immediately since the browser stops sending the expired session id cookie; in which case PHP issues a new session id cookie. The session id file associated with the expired cookie becomes abandoned, does not get accessed anymore; therefore garbage collected anytime as described above.

Last, your specific issue can be resolved (i) by looking at the expiry date of session id cookie (ii) and remembering that cookies with timeout are not renewed when page is visited/refreshed.



来源:https://stackoverflow.com/questions/15197826/session-timeout-issue-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!