tags:

views:

98

answers:

2

I'm having trouble preserving session state for a prolonged period of time. I use sessions to preserve login state. I require the below snippet of code at the top of each of my pages before any other code. First off, is there any settings I'm missing?

session_cache_expire(2880); //set session to expire in 48 hours 
session_start();

Some people are logged out before the 48 hour expiration time. What types of things could cause this? I know closing the browser kills the session and this is not the case.

As far as I can tell it happens when the user is inactive for several hours or more.

Users are never logged off while actively browsing the site.

What gives?

+1  A: 

That only affects how long the browser caches session pages for.

Try setting the gc_maxlifetime variable (value is in seconds):

ini_set("session.gc_maxlifetime", "172800");
Andy Shellam
This is php 5.3 correct? Did I mention I'm using 5.2.5? oops..
payling
Both ini_set and session.gc_maxlifetime have been in PHP since the PHP4 days so they'll work on 5.1, 5.2, 5.3... whatever.
Andy Shellam
oh, I read the manual and it said PHP5 >= 5.3. I didn't read it correctly at first. Thanks!
payling
I'll give this go and accept it if it works out.
payling
That seemed to do the trick, thanks Andy! According to php manual by default maxlifetime is set to 1440 seconds (24 minutes), this was likely the problem.http://www.codingforums.com/archive/index.php/t-99224.htmlThe 2nd post down is an interesting read, I'm not sure if this could be another reason but the frequency of users losing session is better when extending the garbage collection maxlifetime.
payling
+1  A: 

session_cache_expire only effects HTTP cache expiration time. What you want to do is use cookies to set your session data.

The following is an example I have used for login/logout sessions.

<?php

session_start();

if ($action == "logout") {
  setcookie('sId', '', time()-60*60*24*365); //set sId cookie to expire

  session_destroy();
} else if (empty($_SESSION['sId'])) { //if cannot get sId from session
  if (isset($_COOKIE['sId'])) { //check if sId is in cookie
    $sId = $_COOKIE['sId'];
  } else { //get a new sId and set to cookie
    $sId = session_id();
    setcookie('sId', $sId, time()+60*60*24*365);
  }

  $_SESSION['sId'] = $sId; 
} else { //get sId from session
    $sId = $_SESSION['sId'];
}

?>
Keith Maurino
My session variable I store is the user login id, is that a good idea to store that in a cookie?
payling
Cookies are not a great way at all to store session data - especially if it's sensitive because it gets passed to and from the server with every request. It's the session ID that you want to store in the cookies which PHP does as standard, then you use php.ini to customise the session handling (such as timeout) or write your own.
Andy Shellam