4

The Problem:

I have a website that uses PHP sessions to allow users to log in. It works fine. But the session expires too soon that 1 minute of inactivity will log out the user.

My Environment:

Php version: 7.1

Server: NGINX

Framework: CakePHP 3.5

What I did so far?

I did every single solution on the StackOverflow or any search result I get. I extended my session timeout both in php.ini and CakePHP configurations.

The solution

After 2 or 3 days of research, I found the solution. In my php.ini I found a configuration named session.gc_probability and I put value 0 for that. Now my sessions never get expired except if the user logs out intentionally.

And now my current problem is, I don't want my session.gc_probability configuration to be zero as it will not collect any garbage (Not really sure about this. Please correct me if this information is wrong.). And this will cause the sessions to remain for month or years which a real GARBAGE for the server.

I got the idea of giving session.gc_probability zero value from here

session.gc_divisor coupled with session.gc_probability defines the 
probability that the gc (garbage collection) process is started on 
every session initialization. The probability is calculated by using 
gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that 
the GC process starts on each request. session.gc_divisor defaults to 
100.

What is exactly wrong with my configurations? What causes the garbage collection to remove my sessions that soon? session.gc_probability was 1 and session.gc_divisor was 1000. I think a process with 1/1000 probability should not start every 1 or 2 minutes.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
Peshraw H. Ahmed
  • 439
  • 3
  • 22

1 Answers1

2

According to your follow-up comments your setting for Session.handler is php. The Sessions documentation explains:

The built-in configurations are:

  • php - Saves sessions with the standard settings in your php.ini file.
  • cake - Saves sessions as files inside tmp/sessions. This is a good option when on hosts that don’t allow you to write outside your own home dir.

[…]

The default php.ini setting for session.save_path depends on your PHP distribution (and it can be changed anyway) but it normally involves a shared data storage for all PHP applications that do not opt out. That means that the app with the shortest session.gc_maxlifetime is likely to remove session data from other apps.

Switching to cake should address that.


A little follow-up about session.gc_probability and session.gc_divisor. Setting them too aggressively will cause frequent garbage collection. That may harm performance but it won't cause premature data expiration. On the other side, too loose values will still allow access to obsolete data.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360