I have searched for a way to check if a session is started and how long has it been since it was started, and if passes half hour per say regenerate the id, if it passes more than an hour destroy it.
I found this code here on stack:
//Start the session
session_start();
// Check if the session is started, if not regenerate it each time passes 30 minutes
if (!isset($_SESSION['init'])) {
$_SESSION['init'] = time();
} elseif (time() - $_SESSION['init'] > 1800) {
session_regenerate_id(true);
$_SESSION['init'] = time();
}
//Check if the session was alive for more than one hour, if so kill it
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 3600)) {
session_destroy();
session_unset();
}
$_SESSION['last_activity'] = time();
But it seems to run is some problems, I tried destroying it after 18 seconds so I can check if it’s working. When I request the page that is protected and it’s been more than 18 seconds, the first time I’m still being on it but the second time I’m redirected as I am supposed to be the first time after 18 seconds, why is that ?
Did I do something wrong ?
When you run the page the first time, you check if a session is set and then at the end set the session variable. You should put the
$_SESSION['last_activity'] = time();at the beginning. Also, the page will not keep checking if a session variable is expired, so it will only check if you set the variable on one page and check/set it on all of the pages you want protected.