How do I expire a PHP session after 30 minutes?
You should implement a session timeout on your own. Both session.gc_maxlifetime and session.cookie_lifetime are not reliable. The reason for that is:
First:
session.gc_maxlifetime
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.
But the garbage collector is only started with a probability of session.gc_probability devided by session.gc_divisor. And using the default values for that options (1 and 100), the chance is only at 1%.
Furthermore the age of the session data is calculated on the file’s last modification date and not the last access date:
Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.
So it additionally might occur that a session data file is deleted while the session itself is still considered as valid.
And second:
session.cookie_lifetime
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]
This does only affect the cookie lifetime. But the session itself may be still valid. It’s the server’s task to invalidate a session, not the client’s.
So the best solution would be to implement a session timeout on your own:
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
// session started more than 30 minates ago
session_destroy();
$_SESSION = array();
}
You can scrap sessions after a certain lifespan by using the session.gc-maxlifetime ini setting:
ini_set('session.gc-maxlifetime', 60*30);





good article