Set PHP session timeout
There are many different discussions about PHP sessions. We may often face some weird issues while handling PHP sessions. Sometimes session is expired earlier than expected. Or sometimes the session is not expired. This introduces many confusions.
Today we discuss how to set PHP session timeout correctly today. In php.ini, there are three key parameters which will affect the session timeout. session.gc_maxlifetime, session.gc_probability and session.gc_divisor. session.gc_maxlifetime defined the lifetime of a session in seconds which indicates when the session will be garbage collected. Then session.gc_probability and session.gc_divisor will determine the probability an expired session will be garbage collected when a new session to the website is established. When session.gc_probability and session.gc_divisor are equal, then the expired sessions will be garbage collected each time when there is a new session created. But to avoid affecting the performance, session.gc_probability/session.gc_divisor should not be too high.
There are three ways you can set session.gc_maxlifetime:
- session.gc_maxlifetime in php.ini. The default value is 1440 seconds which is 24 minutes;
- ni_set(“session.gc_maxlifetime”, time_in_seconds); -- Put this at the beginning of PHP code
- php_value session.gc_maxlifetime time_in_seconds --Set this in .htaccess if you have no access to php.ini.
The above way to set session timeout is not reliable. The reason for this and why we should implement a session timeout mechanism ourselves can be found at What you may not know about PHP session.
Holly : I need Google in my brain and anti-virus in my heart Layth : And photoshop on your face