Last active
January 1, 2016 12:19
-
-
Save johnbocook/8143367 to your computer and use it in GitHub Desktop.
Expire a PHP Session After X Minutes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) { | |
// last request was more than 30 minutes ago | |
session_unset(); // unset $_SESSION variable for the run-time | |
session_destroy(); // destroy session data in storage | |
} | |
$_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: | |
*/ | |
if (!isset($_SESSION['CREATED'])) { | |
$_SESSION['CREATED'] = time(); | |
} else if (time() - $_SESSION['CREATED'] > 1800) { | |
// session started more than 30 minutes ago | |
session_regenerate_id(true); // change session ID for the current session an invalidate old session ID | |
$_SESSION['CREATED'] = time(); // update creation time | |
} | |
//note that session.gc_maxlifetime should be at least equal to the life time of this custom expiration handler (1800 in this example). | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment