I am creating a session when a user logs in like so:
$_SESSION['id'] = $id;
How can I specify a timeout on that session of X minutes and then have it perform a function or a page redirect once it has reached X minutes??
EDIT: I forgot to mention that I need the session to timeout due to inactivity.
The inactivity of a registered user is checked by the session timeout. When a user login into a website then a session creates for that user and the session is destroyed when the user logout or closes the browser. The session timeout is used to set the time limit for the inactivity of the user.
By default, the PHP session expired when you close the browser or after a specific time. That usually is 24 minutes, but it depends on your server configuration.
If you use PHP's default session handling, the only way to reliably change the session duration in all platforms is to change php. ini. That's because in some platforms, garbage collection is implemented through a script that runs every certain time (a cron script) that reads directly from php.
first, store the last time the user made a request
<?php $_SESSION['timeout'] = time(); ?>
in subsequent request, check how long ago they made their previous request (10 minutes in this example)
<?php if ($_SESSION['timeout'] + 10 * 60 < time()) { // session timed out } else { // session ok } ?>
When the session expires the data is no longer present, so something like
if (!isset($_SESSION['id'])) { header("Location: destination.php"); exit; }
will redirect whenever the session is no longer active.
You can set how long the session cookie is alive using session.cookie_lifetime
ini_set("session.cookie_lifetime","3600"); //an hour
EDIT: If you are timing sessions out due to security concern (instead of convenience,) use the accepted answer, as the comments below show, this is controlled by the client and thus not secure. I never thought of this as a security measure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With