We do not consider cookie expiration times here, only issues related to the PHP garbage collection mechanism. The following three configuration items in php.ini are required:

  1. session.gc_maxlifetime
  2. session.gc_probability
  3. session.gc_divisor

session.gc_maxlifetime

Session. gc_maxLifetime specifies how many seconds elapsed before data is considered “garbage” and cleared. The default is 1440, or 24 minutes. If garbage collector is started, session files whose current time – update time > 1440 are cleared.

Update time of the session

Here is an example of when a session is updated

// session_test.php <? phpif ($_GET['type'] = ='1') {
		session_start();
		$_SESSION['first_name'] = 'Andreas';
		$_SESSION['last_name'] = 'Wang';
    } elseif ($_GET['type'] = ='2') {
		session_start();
		break;
    }
Copy the code
  1. First let’s simulate the login situation by going to localhost/session.php? Type =1, find the value of cookie PHPSESSID by debugging tool;

In the terminal CD/private/var/TMP find store session file directory, through the stat modify_time sess_bidcjuk0uiv3i7rdieo2k6vcbe view the file, “Modify_time” represents the update time of this session

16777220 28699433 -rw------- 1 _www wheel 0 14 "Dec 15 11:03:28 2017" "Dec 15 11:03:28 2017" "Dec 15 11:03:28 2017" "Dec 15 11:03:28 2017" 4096 8 0 sess_bidcjuk0uiv3i7rdieo2k6vcbe
Copy the code

You can see that the modify_time(second time) of the file is Dec 15 11:03:28 2017, when we call localhost/session.php? Type = 2, and then execute the stat sess_bidcjuk0uiv3i7rdieo2k6vcbe, found modify_time changed.

  1. Then delete the cookie and prepare to test the other case
  2. To access localhost/session. PHP? Type =2, that is, session is opened but no value is assigned

Through a simple test, it is concluded that:

  • When a session has a value, session_start() is executed. The session is updated regardless of whether the value of the session is changed.
  • If session_start() is executed without adding a session when there is no value in the session, the session update time remains the same.

The session. Gc_probability and session. Gc_divisor

PHP does not clean up a session immediately after it expires. It only finds the session that expired at that point in time and cleans it up when the GC process is running.

The session.gc_divisor and session.gc_probability configurations determine the probability of starting a GC process on each session initialization (session_start()), The probability is session.gc_probability/session.gc_divisor

By default, the GC only runs session_start() once every 100 times, so by default, only high-traffic sites can clean up expired sessions on time, otherwise, even if the session is expired, because session_start() is executed too few times, Sessions are not cleaned up.