How to destroy / expire session after X minutes in php

In this quick post i am going to share a useful php tips to destroy / expire session after X minutes, If you want to destroy user’s session after x minutes and don’t want to use default session timeout which is 24 minuets. Like as your need to increase session timeout till 40 minutes then use below php snippets.

The best solution is to implement a session timeout on your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it on every request:

function sessionTimeout($duration)
 if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > ($duration * 60))) {
    // last request was more than x minutes ago, where x = duration
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
 }
}
$duration = 40; //40 minute as example
sessionTimeout($duration);
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation-

function sessionRegenerate($duration)
  if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
  } else if (time() - $_SESSION['CREATED'] > ($duration * 60)) {
    // session started more than x minutes ago, where x = duration
    session_regenerate_id(true);    // change session ID for the current session an invalidate old session ID
    $_SESSION['CREATED'] = time();  // update creation time
  }
}
$duration = 40; //40 minute as example
sessionRegenerate($duration);

Note: that session.gc_maxlifetime should be at least equal to the life time of this custom expiration handler (40 minutes in this example).

If you like this post please don’t forget to subscribe my public notebook for more useful stuff

Leave a Reply

Your email address will not be published. Required fields are marked *

Top