Posted By

fackz on 11/05/13


Tagged

session expire


Versions (?)

Who likes this?

12 people have marked this snippet as a favorite

ChristineMeany
fackz
IMPGTX
Priestd09
rmk017
JeffSFO
jameswilliam723
bcmoney
ironcrema
Hgonzalez1988
sucaju
williamhillx


How to expire a PHP session after X minutes?


 / Published in: PHP
 

URL: http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes

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 with every request:

  1. if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
  2. // last request was more than 30 minutes ago
  3. session_unset(); // unset $_SESSION variable for the run-time
  4. session_destroy(); // destroy session data in storage
  5. }
  6. $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
  7.  
  8. /*
  9. You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:
  10. */
  11. if (!isset($_SESSION['CREATED'])) {
  12. $_SESSION['CREATED'] = time();
  13. } else if (time() - $_SESSION['CREATED'] > 1800) {
  14. // session started more than 30 minutes ago
  15. session_regenerate_id(true); // change session ID for the current session an invalidate old session ID
  16. $_SESSION['CREATED'] = time(); // update creation time
  17. }
  18.  
  19. //note that session.gc_maxlifetime should be at least equal to the life time of this custom expiration handler (1800 in this example).

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jamessusan104 on August 22, 2017

On the off chance that i have session factors to tell if a client is on the web yet they have left the PC for X minutes, does the session timeout? If not what is a code to make them timeout if no activity(activity=going to different pages and so on)? assignment help service

Posted By: ChristineMeany on January 12, 2018

wow, great) thanks a lot

Posted By: sucaju on June 2, 2018

Great Work, Thanks

Posted By: johnmathew on July 2, 2018

I have no words to to say, specifically for a motive that it is pretty authentic what you have got written and shared right here. It's everywhere inside everyone who preserve thinking that way as you'll assume out of clear information. I'm a writer and have some good experiences dealing with topics that deals with injustice in terms of human caring between the individuals. I presently work for a best essay writing service and I'm used to write some articles whenever I get some free time.

Posted By: vidyavox on August 19, 2018

I could not resist commenting. Perfectly written! jio4gvoice for windows

Posted By: williamhillx on August 26, 2018

Great work! Simple beautiful!

You need to login to post a comment.