48

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.

user342391
  • 7,569
  • 23
  • 66
  • 88
  • 9
    possible duplicate of [How do I expire a PHP session after 30 minutes?](http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes) – Kzqai Mar 06 '12 at 19:12

8 Answers8

87

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
  }
?>
Jacco
  • 23,534
  • 17
  • 88
  • 105
  • 22
    But the session can timeout before that, if the default session timeout in your PHPINI is shorter than the time you chose. The timeout is often less than an hour by default. If you dont want the client to control the timeout, you need to combine this code with an ini_set of session.cookie_lifetime. This answer also does not handle the case where a client deletes their cookies. – Olhovsky Jul 27 '12 at 11:32
  • 2
    PHP default is '0' which means: "Until the browser is closed". If the browser deletes the cookie, the `$_SESSION['timeout']` var will not be set in the first place. However, I skipped all the other things session management because this question asks about timeout only. – Jacco Sep 08 '12 at 09:50
46

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.

Kaktus
  • 153
  • 4
  • 23
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
  • 1
    you have to remove the quotes around $_SESSION['id'] – Victor Stanciu Jun 18 '10 at 10:18
  • Even though your not the voted answer, your solution seems more secure, my question is this, would you have to set that session timeout on each page? I suppose that would make sense as you would want it to restart each time? Secondly do you have to do session_start for each page to get at session data, or just once to kick it off? Thanks – nagates Jun 28 '11 at 07:25
  • 11
    There are some issues with the session cookie lifetime, most notably, it relies on the *client* to enforce it. The cookie lifetime is there to allow the client to clean up useless/expired cookies, it is not to be confused with anything security related. – Jacco Jul 08 '11 at 12:01
  • @jacco: I'm seconding this, downvote. This is just security through obscurity. – mark Feb 06 '12 at 13:50
  • This answer should be combined with Jacco's answer, to have a complete solution. Jacco's answer does not allow you to modify sessions to be longer than the default, and does not handle the case where a client deletes their cookies. – Olhovsky Jul 27 '12 at 11:35
  • I agree with Olhovsky. THIS was the correct answer that I was looking for: the ini_set value to expire the session lifetime. – akahunahi Apr 12 '13 at 01:36
  • "Session.cookie_lifetime" specifies the lifetime of the client/browser cookie. if you want to set the serverside lifetime use "session.gc_maxlifetime". http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime – Nijboer IT Dec 17 '13 at 08:18
5

Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.

<?php 
   if(!isset($_SESSION["timeout"])){
     $_SESSION['timeout'] = time();
   };
   $st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>

<?php 
  if(time() < $st){
    echo 'Session will last 1 minute';
  }
?>
Community
  • 1
  • 1
2
<script type="text/javascript">
window.setTimeout("location=('timeout_session.htm');",900000);
</script>

In the header of every page has been working for me during site tests(the site is not yet in production). The HTML page it falls to ends the session and just informs the user of the need to log in again. This seems an easier way than playing with PHP logic. I'd love some comments on the idea. Any traps I havent seen in it ?

Byterbit
  • 75
  • 6
  • 2
    If you have multiple tabs opened with the same site, you must refresh them all to create an activity, otherwise if you keep working in 1 tab, others will show "timeout_session.htm" after timeout. Very frustrating, especially if "timeout_session.htm" is unsetting/destroying session . =) – Alex G Sep 08 '16 at 19:00
2
<?php 
session_start();

if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";
}

else{
session_destroy();
session_start();
$_SESSION['time'] = time();
echo "welcome new user";
}
?>
Uday Hiwarale
  • 4,028
  • 6
  • 45
  • 48
1

Byterbit solution is problematic because:

  1. having the client control expiration of a server side cookie is a security issue.
  2. if expiration timeout set on server side is smaller than the timeout set on client side, the page would not reflect the actual state of the cookie.
  3. even if for the sake of comfort in development stage, this is a problem because it won't reflect the right behaviour (in timing) on release stage.

for cookies, setting expiration via session.cookie_lifetime is the right solution design-wise and security-wise! for expiring the session, you can use session.gc_maxlifetime.

expiring the cookies by calling session_destroy might yield unpredictable results because they might have already been expired.

making the change in php.ini is also a valid solution but it makes the expiration global for the entire domain which might not be what you really want - some pages might choose to keep some cookies more than others.

0
<?php
session_start();
if($_SESSION['login'] != 'ok')
    header('location: /dashboard.php?login=0');

if(isset($_SESSION['last-activity']) && time() - $_SESSION['last-activity'] > 600) {
    // session inactive more than 10 min
    header('location: /logout.php?timeout=1');
}

$_SESSION['last-activity'] = time(); // update last activity time stamp

if(time() - $_SESSION['created'] > 600) {
    // session started more than 10 min ago
    session_regenerate_id(true); // change session id and invalidate old session
    $_SESSION['created'] = time(); // update creation time
}
?>
  • Make sure to comment your answer and explain where and how you are adding the timeout. – Rias Apr 21 '15 at 21:20
0
    session_cache_expire( 20 );
    session_start(); // NEVER FORGET TO START THE SESSION!!!
    $inactive = 1200; //20 minutes *60
    if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
    header("Location: user_logout.php");
}
    }
    $_SESSION['start'] = time();

    if($_SESSION['valid_user'] != true){
    header('Location: ../....php');
    }else{  

source: http://www.daniweb.com/web-development/php/threads/124500

khaled_tn
  • 25
  • 1
  • 1
    Just Googling the first answer you come across and pasting it into Stack Overflow isn't conducive to the point of this site. Moreover, session_cache_expire() has nothing to do with the length of your session so the answer you pasted in has incorrect information. – David Bradbury Apr 23 '13 at 15:37
  • @DavidBradbury By default the cookie store the session_id, if cookie expires, the session_id cannot accessed when the client requesting. – LF00 Dec 27 '16 at 05:44