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))) {
    
    session_unset();     
    session_destroy();   
 }
}
$duration = 40; 
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_regenerate_id(true);    
    $_SESSION['CREATED'] = time();  
  }
}
$duration = 40; 
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

Enter your email address to subscribe my public notebook..!!

Join 22,821 other subscribers
Posted in PHP