Home How do I expire a PHP session after 30 minutes?

# How do I expire a PHP session after 30 minutes?

Tom
1#
Tom Published in 2009-02-06 13:14:14Z
 I need to keep a session alive for 30 minutes and then destroy it.
Lode
2#
 You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I'll explain the reasons for that. 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 divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%. Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive. Furthermore, when using PHP's default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, 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 because the session data was not updated recently. And second: session.cookie_lifetime session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […] Yes, that's right. This only affects the cookie lifetime and the session itself may still be valid. But it's the server's task to invalidate a session, not the client. So this doesn't help anything. In fact, having session.cookie_lifetime set to 0 would make the session’s cookie a real session cookie that is only valid until the browser is closed. Conclusion / best solution: The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request: if (isset($_SESSION['LAST_ACTIVITY']) && (time() -$_SESSION['LAST_ACTIVITY'] > 1800)) { // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage }$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp  Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely. You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation: if (!isset($_SESSION['CREATED'])) {$_SESSION['CREATED'] = time(); } else if (time() - $_SESSION['CREATED'] > 1800) { // session started more than 30 minutes ago session_regenerate_id(true); // change session ID for the current session and invalidate old session ID$_SESSION['CREATED'] = time(); // update creation time }  Notes: session.gc_maxlifetime should be at least equal to the lifetime of this custom expiration handler (1800 in this example); if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you'll also need to use setcookie with an expire of time()+60*30 to keep the session cookie active.
Ted Cohen
3#
Ted Cohen Reply to 2013-11-03 13:13:12Z
 Is this to log the user out after a set time? Setting the session creation time (or an expiry time) when it is registered, and then checking that on each page load could handle that. E.g.: $_SESSION['example'] = array('foo' => 'bar', 'registered' => time()); // later if ((time() -$_SESSION['example']['registered']) > (60 * 30)) { unset($_SESSION['example']); }  Edit: I've got a feeling you mean something else though. You can scrap sessions after a certain lifespan by using the session.gc_maxlifetime ini setting: Edit: ini_set('session.gc_maxlifetime', 60*30); Peter Mortensen 4# Peter Mortensen Reply to 2014-04-10 19:39:06Z  if (isSet($_SESSION['started'])){ if((mktime() - $_SESSION['started'] - 60*30) > 0){ //Logout, destroy session, etc. } } else {$_SESSION['started'] = mktime(); } 
Peter Mortensen
5#
Peter Mortensen Reply to 2014-04-10 19:43:08Z

## Simple way of PHP session expiry in 30 minutes.

Note : if you want to change the time, just change the 30 with your desired time and do not change * 60: this will gives the minutes.

In minutes : (30 * 60)
In days : (n * 24 * 60 * 60 ) n = no of days

<?php
session_start();
?>

<html>
<form name="form1" method="post">
<table>
<tr>
<td><input type="text" name="text1"></td>
</tr>
<tr>
</tr>
<tr>
<td><input type="submit" value="SignIn" name="submit1"></td>
</tr>
</table>
</form>
</html>

<?php
if ($_POST['submit1']) {$v1 = "FirstUser";
$v2 = "MyPassword";$v3 = $_POST['text'];$v4 = $_POST['pwd']; if ($v1 == $v3 &&$v2 == $v4) {$_SESSION['luser'] = $v1;$_SESSION['start'] = time(); // Taking now logged in time.
// Ending a session in 30 minutes from the starting time.
$_SESSION['expire'] =$_SESSION['start'] + (30 * 60);
} else {
}
}
?>


## HomePage.php

<?php
session_start();

if (!isset($_SESSION['luser'])) { echo "Please Login again"; echo "<a href='http://localhost/somefolder/login.php'>Click Here to Login</a>"; } else {$now = time(); // Checking the time now when home page starts.

if ($now >$_SESSION['expire']) {
session_destroy();
}
else { //Starting this else one [else1]
?>
<!-- From here all HTML coding can be done -->
<html>
Welcome
<?php
echo $_SESSION['luser']; echo "<a href='http://localhost/somefolder/logout.php'>Log out</a>"; ?> </html> <?php } } ?>  ## LogOut.php <?php session_start(); session_destroy(); header('Location: http://localhost/somefolder/login.php'); ?>  habamedia 6# habamedia Reply to 2014-05-26 11:32:51Z  It's actually easy with a function like the following. It uses database table name 'sessions' with fields 'id' and 'time'. Every time when the user visits your site or service again you should invoke this function to check if its return value is TRUE. If it's FALSE the user has expired and the session will be destroyed (Note: This function uses a database class to connect and query the database, of course you could also do it inside your function or something like that): function session_timeout_ok() { global$db; $timeout = SESSION_TIMEOUT; //const, e.g. 6 * 60 for 6 minutes$ok = false; $session_id = session_id();$sql = "SELECT time FROM sessions WHERE session_id = '".$session_id."'";$rows = $db->query($sql); if ($rows === false) { //Timestamp could not be read$ok = FALSE; } else { //Timestamp was read succesfully if (count($rows) > 0) {$zeile = $rows[0];$time_past = $zeile['time']; if ($timeout + $time_past < time() ) { //Time has expired session_destroy();$sql = "DELETE FROM sessions WHERE session_id = '" . $session_id . "'";$affected = $db -> query($sql); $ok = FALSE; } else { //Time is okay$ok = TRUE; $sql = "UPDATE sessions SET time='" . time() . "' WHERE session_id = '" .$session_id . "'"; $erg =$db -> query($sql); if ($erg == false) { //DB error } } } else { //Session is new, write it to database table sessions $sql = "INSERT INTO sessions(session_id,time) VALUES ('".$session_id."','".time()."')"; $res =$db->query($sql); if ($res === FALSE) { //Database error $ok = false; }$ok = true; } return $ok; } return$ok; } 
Pablo Pazos
7#
Pablo Pazos Reply to 2014-10-07 03:52:04Z
 This post shows a couple of ways of controlling the session timeout: http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions IMHO the second option is a nice solution: 
Alpesh Rathod
8#
Alpesh Rathod Reply to 2015-05-21 11:20:50Z
 Store a timestamp in the session  0) { $array = mysql_fetch_assoc($result); session_start(); $_SESSION['user_id'] =$user; $_SESSION['login_time'] = time(); header("Location:loggedin.php"); } else { header("Location:login.php"); } ?>  Now, Check if the timestamp is within the allowed time window (1800 seconds is 30 minutes)  1800) { header("Location:login.php"); } else { // uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login //$_SESSION['login_time'] = time(); echo ( "this session is ". $_SESSION['user_id'] ); //show rest of the page and all other content } ?>  Touqeer Shafi 9# Touqeer Shafi Reply to 2015-07-15 06:16:41Z  Well i understand the aboves answers are correct but they are on application level, why don't we simply use .htaccess file to set the expire time ?  #Session timeout php_value session.cookie_lifetime 1800 php_value session.gc_maxlifetime 1800  edwardmp 10# edwardmp Reply to 2017-05-01 13:30:48Z  Use the session_set_cookie_paramsfunciton for make this. Is necessary calling this function before session_start() call. Try this: $lifetime = strtotime('+30 minutes', 0); session_set_cookie_params($lifetime); session_start();  See more in: http://php.net/manual/function.session-set-cookie-params.php lnepal 11# lnepal Reply to 2016-08-26 06:55:45Z  Please use following block of code in your include file which loaded in every pages. $expiry = 1800 ;//session expiry required after 30 mins if (isset($_SESSION['LAST']) && (time() -$_SESSION['LAST'] > $expiry)) { session_unset(); session_destroy(); }$_SESSION['LAST'] = time(); 
 You need to login account before you can post.
Processed in 0.350593 second(s) , Gzip On .