how to expire php session if user is inactive for 15 mins
Call below function in your header file, so that whenever user does any activity at that time page gets refreshed and check whether session time outs or not.
function auto_logout($field)
{
$t = time();
$t0 = $_SESSION[$field];
$diff = $t - $t0;
if ($diff > 1500 || !isset($t0))
{
return true;
}
else
{
$_SESSION[$field] = time();
}
}
Use something like this in header
if(auto_logout("user_time"))
{
session_unset();
session_destroy();
location("login.php");
exit;
}
User_time is the session name. I hope this answer will help you. What actually this code does is : "Checks whether diff is greater than 1500 seconds or not. If not then set new session time." You can change time diff(1500) according to your requirement.
Need PHP session_start to expire in 15 minutes
get current time in your session when user logged in
$_SESSION['user_time']=time()
next create function and share in your pages you want to be protected
function isSessionExpired()
{
if(time()-$_SESSION['user_time']>(15*60))
{
/... your actions here for example unset session or user
}
}
that's all!
How do I expire a PHP session after 30 minutes?
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 oftime()+60*30
to keep the session cookie active.
Automatic Logout after 15 minutes of inactive in php
This is relatively easy to achive with this small snippet here:
if(time() - $_SESSION['timestamp'] > 900) { //subtract new timestamp from the old one
echo"<script>alert('15 Minutes over!');</script>";
unset($_SESSION['username'], $_SESSION['password'], $_SESSION['timestamp']);
$_SESSION['logged_in'] = false;
header("Location: " . index.php); //redirect to index.php
exit;
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}
User Inactivity Logout PHP
You could also do:
$_SESSION['loginTime'] = time();
On every page, and when the user is trying to navigate and he has been inactive for an twenty minutes you can log him out like this:
if($_SESSION['loginTime'] < time()+20*60){ logout(); }
How to Force log out php session after x minutes (not inactive log out)
Normally, PHP only executes in response to HTTP requests, and therefore sessions are not cleaned until a request arrives. When and how this is done is configured using the session configuration parameters.
While you cannot directly run the session management code, you can cause it to run by configuring the parameters and then simulating a request via cron
or a similar tool. Ping your server every minute (or whatever) with an unpublished URL request that sets session.gc_probability
to 100 and then starts a session. This will cause the session management code to garbage collect the sessions--which will effectively cleanup any timed out sessions.
Related Topics
Getting Data Posted in Between Two Dates
Why Are $_Server["Php_Auth_User"] and $_Server["Php_Auth_Pw"] Not Set
Have Gd Get Image from Binary String
Forbidden :You Don't Have Permission to Access /Phpmyadmin on This Server
How to Print the Actual Query That MySQLi->Execute() Makes
Supplied Argument Is Not a Valid MySQL Result Resource
Curl_Exec Printing Results When I Don't Want To
Cannot Call Function SQLsrv_Connect()
How to Insert Multiple Rows Using Prepared Statements
What Is Unexpected T_Variable in PHP
Parse Timezone Int to String (Timezone Name) (Facebook API)
How to Enable Shell_Exec and Exec on PHP
How to Force Formrequest Return JSON in Laravel 5.1
Creating Variable Name by Concatenating Strings in PHP