Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Session timeout

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.

like image 765
user342391 Avatar asked Jun 18 '10 10:06

user342391


People also ask

What is PHP session timeout?

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.

How long is PHP session timeout?

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.

How increase session expire time in PHP?

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.


2 Answers

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   } ?> 
like image 189
Jacco Avatar answered Sep 24 '22 13:09

Jacco


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.

like image 22
Vinko Vrsalovic Avatar answered Sep 23 '22 13:09

Vinko Vrsalovic