PHP Session timeout

user342391 picture user342391 · Jun 18, 2010 · Viewed 237.2k times · Source

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.

Answer

Jacco picture Jacco · Jun 18, 2010

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
  }
?>