2

I'm new to sessions and PHP. I know how to set the expiration of a cookie. I wanted to know how is something similar done for a session.

Zacky112
  • 8,679
  • 9
  • 34
  • 36

4 Answers4

3

To ensure it'll not expire before its time

If you're using cookies for sessions, you use session_set_cookie_params to set the expiration time of the corresponding cookie.

You'll also need to change session.gc-maxlifetime and quite possibly session.save_path, though it may vary if you're not using the file sessions save handler.

To ensure it'll not expire after its time

This will guarentee a minimum duration for the session, but you must also save in the session itself when it will expire and check against that to make sure the session doesn't last more than it's supposed to.

This is because:

  • The expiration date of the cookie may have been tempered with (extended by the user).
  • session.gc-maxlifetime doesn't guarentee the expired session will be garbaged collected after that period and it refers to a maximum lifetime of inactivity, not total duration.

So you have to also check server-side whether the session is valid – see this answer.

Community
  • 1
  • 1
Artefacto
  • 96,375
  • 17
  • 202
  • 225
2
session_start();

// 10 mins in seconds
$timeout = 600; 

if(isset($_SESSION['timeout']) ) {
  // Check if session timed out
  $session_time = time() - $_session['timeout'];

  if($session_time > $timeout)
  {  
     // If it did, destroy it and probably logout user
     session_destroy();
     header("Location: logout.php");
  }
}

$_SESSION['timeout'] = time();
Michael S.
  • 305
  • 4
  • 17
  • This a great answer for one half of the answer -- i.e, how to make sure the session doesn't last more than it's supposed to. – Artefacto Jul 12 '10 at 11:51
  • Well, I guess it's one possible interpretation, but you may not want to specify an expiry time of 60 minutes when session.gc_maxlifetime is 1440 seconds, which makes the session able to expire after 24 minutes of inactivity. – Artefacto Jul 12 '10 at 12:03
2

You could use this:

// Change the session timeout value to 30 minutes
ini_set(’session.gc_maxlifetime’, 30*60);

You can also set other option, see doc: http://fr.php.net/manual/en/function.ini-set.php

Crae
  • 33
  • 1
  • 7
1

You can save last session seen date_time for this session and compare it when you have session activity.

But you may want use session_set_cookie_params() function and documentation for it you can find at http://php.net/manual/en/function.session-set-cookie-params.php

Svisstack
  • 16,203
  • 6
  • 66
  • 100