session.gc_maxlifetime vs. session.cookie_lifetime [PHP]

PHP and sessions: Very simple to use, but not as simple to understand as we might want to think.

session.gc_maxlifetime

This value (default 1440 seconds) defines how long an unused PHP session will be kept alive. For example: A user logs in, browses through your application or web site, for hours, for days. No problem. As long as the time between his clicks never exceed 1440 seconds. It's a timeout value.

PHP's session garbage collector runs with a probability defined by session.gc_probability divided by session.gc_divisor. By default this is 1/100, which means that above timeout value is checked with a probability of 1 in 100.

session.cookie_lifetime

This value (default 0, which means until the browser's next restart) defines how long (in seconds) a session cookie will live. Sounds similar to session.gc_maxlifetime, but it's a completely different approach. This value indirectly defines the "absolute" maximum lifetime of a session, whether the user is active or not. If this value is set to 60, every session ends after an hour.


Example:

ini_set('session.gc_maxlifetime', 200000);

1. This value is for the server.
2. It is a settings for Session Garbage Collection.
3. If the users last visit happened before 200000s then this session is eligible for garbage collection.
4. Since it is GC, the session value may be discarded and not compulsory. If a GC action happens after the session was made eligible for the GC, it will be deleted.

ini_set('session.cookie_lifetime', 2000000);

1. This value is for the browser.
2. This is the absolute maximum time till which a browser can keep this cookie active.
3. A 0 value here means immediate or when the browser is closed.

If the user doesn't hit the server back in 2.3 days, his session will be deleted when the session garbage collection runs.
If he keeps on hitting one page on the server every 2.2 (less than 2.3 days) then his session will stay active. But it can be active only until 23 days from the time the session was first generated.
So what that means is session.cookie_lifetime is the absolute maximum lifetime of a session.


References:

http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/session.configuration.php

Comments