2

This is NOT the ordinary question of session_set_cookie_params, or session.gc_maxlifetime. I dug Google and I understood nothing.

The scenario is rather common and usual: I want users sessions to keep working as long as the period "between clicks" is less than ten minutes, even if they stay working for hours.

What I do in each request is the following:

session_name('session_cookie_name');
session_set_cookie_params(600, '/'); // 600 is how much seconds in a ten minutes.
session_cache_limiter(FALSE);
session_start();

And I expect the result I mentioned above, given that session.gc_maxlifetime is set to its default value, 1440

EDIT:

what I got is, every 600 seconds I get a new session without data saved from prevous requests.

What is the convention used to achieve that?

doc_id
  • 1,363
  • 13
  • 41
  • possible duplicate of [How to change the session timeout in PHP?](http://stackoverflow.com/questions/8311320/how-to-change-the-session-timeout-in-php) – doc_id Feb 22 '15 at 15:37

3 Answers3

3

Using setcookie, set a cookie with the same parameters that PHP sets with session_start:

  1. same session cookie name (PHP defaults to PHPSESSID)
  2. same session id, obtained by session_id()
  3. the new expire value (in this case time() + $lifetime )
  4. same path (such as "/") and domain (often $_SERVER['HTTP_HOST'])
doc_id
  • 1,363
  • 13
  • 41
3

Well, your current solution cannot guarantee that session will be collected by GC strictly after 10 minutes have passed by definition.

The better solution is to use default session life time (20 minutes or more) and handle timeout between clicks manually.

Just store $_SESSION['last_click_time'] = time(); and compare it. If more than 600 seconds passed - do what you need: refresh session, logout user, create a log record, email someone, etc.

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • Thanks. But no, I do want to delay the GC, given that I set cookie lifetime to 0. I want to schedule GC to run after the period it would keep alive in case of a new session. How can I? Should I regenerate session id? – doc_id Oct 20 '11 at 01:38
  • @rahmanisback: GC is not called **exactly on time**. Any **real** reason to not follow my advice? – zerkms Oct 20 '11 at 02:01
  • Ignoring the GC probability, this will cause the GC to run over the session data after 20 minutes. I want to let users keep working for hours or days. Are you saying to set session.gc_maxlifetime to a very high value? – doc_id Oct 20 '11 at 02:25
  • @rahmanisback: no. If I wanted to have data persisted for days - I would store it in database, and just load into session (if new has been generated) – zerkms Oct 20 '11 at 02:39
0
$cur_time = time();
if($cur_time > $_SESSION['timeout']){
 //destroy the session (reset)
 session_destroy();
}else{
  //set new time
  $_SESSION['timeout'] = time() + 600;
}

This is what I would do.

donutdan4114
  • 1,262
  • 1
  • 8
  • 16