Tuesday, September 27, 2011

Manually Set PHP Session Timeout — PHP Session

SkyHi @ Tuesday, September 27, 2011
To find out what the default (file-based-sessions) session timeout value on the server is you can view it through a ini_get command:
// Get the current Session Timeout Value
$currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);
Change the Session Timeout Value
// Change the session timeout value to 30 minutes  // 8*60*60 = 8 hours
ini_set(’session.gc_maxlifetime’, 30*60);
// php.ini setting required for session timeout.
//if you want to change the  session.cookie_lifetime.
//This required in some common file because to get the session values in whole application we need to write session_start();  to each file then only will get $_SESSION global variable values.
// Reset the expiration time upon page load //session_name() is default name of session PHPSESSID
if (isset($_COOKIE[session_name()]))
setcookie(session_name(), $_COOKIE[session_name()], time() + $sessionCookieExpireTime, “/”);
//To get the session cookie set param values.
$CookieInfo = session_get_cookie_params();
echo “

echo “Session information session_get_cookie_params function :: 


echo “
Some Description of session related setting for php.ini file.
session.gc_maxlifetime integer
session.gc_maxlifetime specifies the number of seconds after which data will be seen as ‘garbage’ and cleaned up. Garbage collection occurs during session start.
session.cookie_lifetime integer
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means “until the browser is closed.” Defaults to 0. See also session_get_cookie_params() and session_set_cookie_params(). Since the cookie is returned by the browser, it is not prolonged to suffice the lifetime. It must be sent manually by setcookie().

After recieving a "bogus" mark on a bug report i've tried to find out the differences between cache_expire and what was causing a session delete after 24 minutes.

cache_expire is used for cached session pages and has nothing to do with the session data

The garbage collector controls the session data and destroys sessions which are older then 1440 seconds (24 minutes) by default.

So to keep a session alive longer then 24 minutes (for example when a visitor tries to POST a huge message that took him 1 hour to type), you must modify the session.gc_maxlifetime thru ini_set()

Somehow i couldn't find anything in the PHP documentation regarding this and due to that me (and i think many others) got the wrong ideas regarding PHP sessions.
A few examples to fix session timeout are already posted below but in my opinion they all missed session.gc_maxlifetime