3

My php session is set to expire when user closes the browser but I noticed that if I leave my browser open for an extended period of time (24+ hours for example) the session still persists.

Is there a way that I can have these sessions expire either when the browser is closed or when some extended period of time has transpired?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Chris
  • 11,780
  • 13
  • 48
  • 70
  • 2
    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) – Palantir Sep 23 '10 at 12:12
  • When browser closed: No, doesn't work like that. Otherwise see the question linked to by Palantir. – fredley Sep 23 '10 at 12:17
  • @fredley: What do you mean no it doesnt work like that? When I view my cookies, I have my php sessid set to expire when browser closes. – Chris Sep 23 '10 at 12:18
  • 2
    See here too http://stackoverflow.com/questions/777767/firefox-session-cookies – Palantir Sep 23 '10 at 12:23

1 Answers1

6

The solution might be to set data via ini_set('session.gc_maxlifetime', <lifetime in seconds>); Of course if it's possible to change config via PHP. Otherwise you wil need to set proper values in your php.ini:

ini_set(‘session.gc_maxlifetime’,30);
ini_set(‘session.gc_probability’,1);
ini_set(‘session.gc_divisor’,1);

The other approach is setting validity of session cookie by:

$expire=24*60*60;
session_set_cookie_params($expire);
session_start();
Karol Janyst
  • 356
  • 2
  • 10
  • The garbage collector is the way to go, because when you fiddle with cookie lifetime the cookie won't disappear on browser close. Be sure to call `session_regenerate_id()` on unauthorised users, to prevent session-fixation. – Wrikken Sep 23 '10 at 13:03
  • @Wrikken are you suggesting to call session_regenerate_id anytime I catch a user that is not-authorized ? – Chris Sep 23 '10 at 14:05
  • using 1 for divisor and probability would ensure that we are always checking for garbage which would be cpu intensive right? – Chris Sep 23 '10 at 14:07
  • @chris: you could do it based on a variable in the `$_SESSION` array: `session_start();if(!isset($_SESSION['id_generated_by_server'])){ session_regenerate_id(); $_SESSION['id_generated_by_server'] = true;}` – Wrikken Sep 23 '10 at 14:13
  • It's not a good idea to depend on the garbage collector to do your timeouts for you. It only fires up on a *RANDOM* schedule. Best to put some timeout checking into your session handler itself, and force re-auth or something if the idle period exceeds the timeout. – Marc B Sep 23 '10 at 17:16