Wednesday, 8 August 2018

How To Expire PHP Sessions.

This is a simple guide on how to expire user sessions in PHP after a set amount of time. For example purposes, I am going to assume that you want to expire a user’s session after 30 minutes of inactivity.
Unfortunately, with PHP, you will need to manually expire a user’s session. I’ll explain why later on. For now, let’s have a look at the example code:

Here is a quick drill-down of the session expiry code above:
  1. We start our session with session_start(), like always! Remember: You cannot access session variables until the session has been started.
  2. For this example, I set the expiry limit to 30 minutes. You can change this number to 40 minutes or 60 minutes if you wish.
  3. Using the function isset, we check to see if a session variable called “last_action” exists. It is important to verify that this variable exists before we attempt to carry out any calculations on it!
  4. Inside the IF statement, we calculated the number of seconds that have passed since the user was last active. To do this, we subtracted the “last_action” timestamp from the current timestamp.
  5. We then converted our $expireAfter variable into seconds by multiplying it by 60. This is important as it allows us to compare the seconds that have passed against the maximum amount of seconds that are allowed to pass before the session should be expired.
  6. We compared the two values. If $secondsInactive is larger than or equal to $expireAfterSeconds, the user has been inactive for too long and we need to take action.
  7. IF the user has been inactive for too long, we destroy the current session by calling the functions session_unset and session_destroy.
  8. Finally, we reset the last activity variable by assigning the current timestamp to it.

session.gc_maxlifetime doesn’t work

Some of you are probably wondering why I didn’t recommend the usage of session.gc_maxlifetime, which is a configuration option that exists inside the php.ini file. You see, the problem with session.gc_maxlifetime is that it doesn’t do what most PHP developers “expect” it to do. A lot of people tend to assume that it’s an easy way of getting PHP to automatically expire sessions after a set period of time. For example, setting it to:
…should automatically expire all PHP sessions after 30 minutes, right?
Unfortunately, this isn’t the case, as this session expiry relies on PHP’s garbage collection (that’s what the gc in gc_maxlifetime stands for). The problem is, PHP’s garbage collection has a 1% chance of being called, per request (default values). This means that you can never rely on it to automatically expire user sessions.
To put that into perspective, if you have 100 users that have been inactive for longer than 30 minutes, only one of them will have their session expired.

0 comments:

Post a Comment