PHP sessions are handy little things, however it’s a bit tricky to correctly get a custom timeout to work correctly. There are a few key ini settings:
session.gc_maxlifetime -This setting (in seconds) tells the PHP garbage collector how long to keep the session valid.Â The default is 24 minutes.
session.gc_probability – The probability that the garbage collector will run and clean up old session data.Â The default value is 1.
session.gc_divisor – The divisor to use with the probability.Â The default value is 100.
session.save_path – The path for session values to be saved.Â The default is /tmp, however it is important to change this to a custom folder for the application – especially if you are in a shared hosting enviorment.Â The garbage collector does not discriminate, and it will delete ANY session data that is older than the set limit, not just ones that correspond to your application.
session.cookie_lifetime – How long to keep the cookie written to the client machine valid.Â Defaults to 0, which means the cookie will expire at the end of the broswer session (at logout or when closing the broswer).
Now, before you start anything, make sure you have a writable folder setup for your application that you can use to store your session data.
Start your session with something smiliar to:
Setting the above configuration well make sure your session files are saveed in a seperate folder, they will expire in 24 hours, and the garbage collector will run everytime session_start is called to cleanup expired sessions.
The problem with alot of other infomormation is that they will suggest setting the cookie_lifetime to be the same as the gc_maxlifetime.Â The problem with this is that when the cookie value is set, the expiration date is not updated as the user continues to be active in the application.Â The session data on the server side is updated.Â So, if this is the case, after the value of cookie_lifetime has expired, even if the session data on the server was just updated, your session will be invalid, and you will be required to login again.
I hope that this post will help someone else in the quest to conquer the php session timeout.Â It definitely is not very clear, and can be very confusing!