Disconnect a user after 5mins - php

Can somebody please help me on how to disconnect a user (using sessions) after 5mins regardless of being idle or active.thank you
am coding in php and mysql as the database.

When the user logs on, you could register a session variable for the time, every time a page is loaded, check if 5 minutes has elapsed since logging on.
For example:
<?php
session_start();
if($_SESSION["loggedin"] && ($_SESSION["timer"]<(time()-(5*60)))) {
logout();
}
function login() {
//do login stuff
$_SESSION["timer"]=time();
}
function logout() {
//do logout stuff
}
?>

Use session.gc-maxlifetime:
ini_set('session.gc-maxlifetime', 60*5);
Once above line is read by the php interpreter, your session will expire after 5 minutes.

You can save a timestamp of the last action in the $_SESSION array and compare $timestamp + 300 with the current time.
Just setting the garbage collector lifetime to a low value won't work because the garbace collector doesn't run on every page request.

Related

PHP Application logs out within seconds

I have a PHP/MySQL application which processes a lot of data. When I use session regeneration, my application logs the user out over and over again within a matter of seconds.
To resolve this, I disabled the session regeneration. I have set gc maxlifetime = 86400.
Could it be possible that a memory leak or long execution time of some heavy PHP script/loop which is not coded properly be at the source of this problem?
function checklogin()
{
if ( isset($_SESSION['LAST_ACTIVITY']) && ( time() - $_SESSION['LAST_ACTIVITY'] > 86400 ) )
{
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
}
function login()
{
session_start();
// session_regenerate_id(); //ON USING IT LOGSOUT, SO I STOPPED USING THIS
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
}
I need to use the session regeneration but it shouldn't log out.
session_start() must be the first instruction execute ever if you want work with cookies.

Logout an inactive user using PHP

I am trying to log a user out of my CMS after a set amount of time. By inactive I mean has not clicked the mouse or typed on there keyboard. So after 30 minutes of inactivity my log out function is ran.
There is already a log out function built in to the CMS I am using -
<?php
session_start();
if (isset($_SESSION['user_id'])){
$login = 1;
}else{
$login = 0;
}
function confirm_logged_in() {
if (!isset($_SESSION['user_id'])) {
//redirect
header("Location: /_cms/login.php?login=0");
}
}
function logout(){
$_SESSION = array();
if(isset($_COOKIE[session_name()])){
setcookie(session_name(), '', time()-4200, '/');
}
session_destroy();
}
?>
Someone else wrote this code and it works. However I don't know the exact time it takes to log out an inactive user. The preset time is - 4200. What I want to find out is how long that takes to logout and if I can change it to any time I want. Can anyone advise?
The -4200 is just to destroy the cookie. Cookies are destroyed by setting a time in the past for them. So setting 4200 seconds backwards is just as effective as 1 second backwards.
To logout users there are multiple methods. You can have a your own cookie set with the last active time (set the time every time the user visits a page). At the beginning of each script include a function which gets this cookie and checks the value which should contain the last active time. If this time is older than your allowed inactive time, then destroy this cookie and destroy your session as well, if not, then update the value to the current time.
Of course, you can also store inside the session itself the last active time, which is a much more efficient way removing the overhead of cookie transfer and management.
EDIT
Below is a minimal code to check for the last active time and logout the user:
function login(){
//check login username/pass etc...
$_SESSION['last_active_time'] = time();
}
function auth(){
if($_SESSION['last_active_time'] < (time() - 1800)){ //1800 is 30 minutes (time in seconds)
logout(); //destroy the session in the logout function
}
else{
$_SESSION['last_active_time'] = time();
}
//do some auth related things
}
That's the basic logic behind this. Of course you would need to implement other stuff you need along with security, checking, etc....
I will try to answer your question and have some questions too.
What CMS are you using? If you can name the CMS, we can provide detailed and accurate solution
Regarding your function logout() and about the setcookie and -4200, whenever you call the function logout, it is checking if there is any coockie set. If yes, then it is just setting the EXPIRY TIME to 4200 seconds ago ie 7 minutes ago from current time. ie. It invalidates the Coockie which is present at present.
Refer the link: http://php.net/manual/en/function.setcookie.php
Now, what you want is that after 30 mins of inactivity, user should be logged out. Your current code is not built for that. You should write the logic to keep checking the last active time and should invoke the logout function if it is more than 30 mins. Now the question is, how to do? Am just modifying your code a bit
if (isset($_SESSION['user_id'])){
$login = 1;
// If the user has performed action within 30 minutes
if($_SESSION['last_active_on'] > (time() - (30*60))){
$_SESSION['last_active_on'] = time(); // Re-set the current time as Last Active
}else{
// User has done some action after 30 minutes.
logout(); // Invoke the Logout functionality
}
}else{
$login = 0;
}
Remember: time() Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
You have not added your login function here. You should modify your login function and should add one more line in that as
$_SESSION['last_active_on'] = time();
One more thing. All this can happen only if the requests are sent to the server. For example: Assume at 4:00 PM, due to some action, there was a server call. Assume at 4:25 you are moving your mouse cursor or clicking anywhere on the page, but if it doesn't send any request to server, then it is considered as in-active itself. And at 4:35 PM if the user does something where the request is sent to server [Normal request or Ajax],
then as per the server, it is 35 mins inactive state, hence it will logout. Hope this answers your question.
You can even refer the SO question: User Inactivity Logout PHP It may also help you.

PHP: pop show that app server time out

I have a PHP app written in codeIgniter. Getting some complaints from clients about the app timing out. Their session times out after two hours of inactivity and they can't seem to remember that.
Is there a way and if so, how, to show a pop up message when a users session has timed out?
Thank you in advance.
PHP cannot display a pop up by itself, but you could probably have a JavaScript query the session status and display a pop up when the session is expired, or even better, count the time since the session opened and let the user know in advance that his session is about to time out
If you want change the duration of the session, see this line in your config.php
$config['sess_expiration'] = 7200;
7200 is 120 minutes * 60 seconds. If you change it to 0, the session will not expire.
To add a warning, the very simplest method would probably to add a JavaScript similar to
setTimeout(function(){alert("Your session will expire in 5 minutes")},6900000); // 6900 seconds (115 minutes) * 1000 milliseconds
You could do it using:
Javascript function using timers (and show a popup after a period of time)
In PHP using a timer set in your $_SESSION and calculate the difference in timestamps (when the user is redirected to a login page, pass a message "Your session has timed out")
A hard-timeout/page redirect using a meta equiv tag to a session-timeout page.
You can even go as far as offering different timeout periods for different user groups...
An example using PHP, which logs them out, tells them and redirects once they log back in:
// get time now
$now = time();
// Set session period
$autologout = '7200';
if (isset($_SESSION["TimeOut"]))
{
if ($now > $_SESSION["TimeOut"])
{
// Unregister session and set message
session_unregister("authenticatedUser");
session_register("loginMessage");
$loginMessage = "Your session has timed out";
// Capture request URL and store in a cookie so that they
// are logged back into the page they were requesting
$requestURL = $_SERVER[REQUEST_URI];
setcookie("requestURL",$requestURL,"0",'/','',FALSE,TRUE);
// Redirect back to login page
header("Location: " . $loginScript);
exit;
} else {
$_SESSION['TimeOut'] = ($now + $autologout);
}
} else {
$_SESSION['TimeOut'] = ($now + $autologout);
}
This presumes that your system session timeouts are longer or set otherwise. It's not written for codeIgnitor either, but hopefully helpful to understand what can be done to soften the blow of session expiry.
Probarly your session maxlifetime is 2 hours.
You can edit that with this: (replace 8 with the max lifetime in hours).
ini_set(’session.gc_maxlifetime’, 8*60*60);

PHP session_id() not accepting existing session id

I'm having trouble forcing sessions to restart in PHP. Here's the problem:
I can get my session id with session_id(), copy it, and add to the very top of my script:
session_id('the_session_id');
session_start();
And when I open a new browser, the session from the other browser is not carried over. What settings can I check?
Reason:
If you close the browser window and open it again, then at this moment a second session is started with a different ID, if the used web application has some session based authentication system the user has to login again. At the same time the user has to logout twice!
Solution:
This function will use a real cookie for the session ID and updates the expiration time with every script execution. The expiration is equal to the PHP directive "gc_maxlifetime" (default) or every custom value. So, put this function in your PHP file. We will need it.
<?php
// $expire = the time in seconds until a session have to expire
function start_session($expire = 0)
{
if ($expire == 0)
$expire = ini_get("session.gc_maxlifetime");
else
ini_set("session.gc_maxlifetime", $expire);
if (empty($_COOKIE['PHPSESSID']))
{
session_set_cookie_params($expire);
session_start();
}
else
{
session_start();
setcookie("PHPSESSID", session_id(), time() + $expire);
}
}
?>
Now, in the top of your page where you're issuing session_id('the_session_id'); and session_start();, remove those lines and start session with this code below:
To start a session with an expire time given by the php configuration
start_session();
To start a session that will expire in 1 hour:
start_session(3600);

User Inactivity Logout PHP

I want my users to be logged out automatically after X minutes of inactivity. I also want to have all sessions destroyed.
How can this be done? How can I check for inactivity then perform a function to log them out???
I tired Michiels approach and got no where.
On investigation I saw that the if statement simply added the expiry period to the current time so the statement never fired.
This is my altered version:
set this when logging in user or loading a secure page:
$_SESSION['expire'] = time()+1*60;
And use this to see if the expiry time is less than current time (i.e we're past the expiry limit):
if(time() > $_SESSION['expire']){
$user -> logout();
}
You can set session time out limit like:
ini_set('session.gc_maxlifetime',30);
Here is the possible solution for you.
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(); }
Depending on how fast your server is and how many users you have, you can have it send a request to your server whenever a user does anything (navigates, clicks a button, whatever). From this request, update a SQL table with their last activity time.
Have a cron job run through the table at some regular interval and delete the sessions of the users that have been inactive for whatever your threshold is going to be.
If your server is slow or you have a lot of users, you can have this script run infrequently.
PHP's session mechanism already have a garbage collector based on the inactivity timeout. You have no worry about.
You can set the last active time by $_SESSION['lastactive'] = time() and update it every time when user navigates to a new page. Then you can have a function timeout() on every page .
function timeout()
{
$maxtime = 60*2; // Here , maxtime has been set to 2 minutes
if(isset($_SESSION['lastactive']) and (time() - $_SESSION['lastactive'] > $maxtime )) // subtracting current time from lastactive time and seeing if it exceeded timeout limit.
{
signout(); //logging out
}
if(isset($_SESSION['lastactive']) and (time() - $_SESSION['lastactive'] < $maxtime )) // subtracting current time from lastactive time and seeing if it exceeded timeout limit.
{
return 1; // timeout limit not exceeded
}
else
{
if(!isset($_SESSION['lastactive']))
{
$_SESSION['lastactive'] = time(); //if lastactive is not set
}
}
}
Use unset($_SESSION['NAME']); or session_destroy();. You could also change the value of the session.
To do this at a certain time, you would need to set a timestamp in the database, and then call it to check if it's beyond X minutes. Look at the link at the bottom.
I'd personally just use cookies and make them expire at a certain time, but whatever floats your boat.
If current time is more than 30 seconds past time X (from the database)
$(document).ready( function()
{
setTimeout(function() { CALL LOGOUT.PHP VIA AJAX }, 720000);
});
720000 means 12 minutes ( for illustration purpose )
put this script in your header and set ur own time of inactivity
you can set what time u want , it will be work like
if you set 5 minutes then when u login to system then it start count for 5 min. but if u click on any module this script will be reloaded , because when page turns then header is also reload when script is reload then it start count from 0 (initial), but if u cant access the system within 5 min. then it will load the logout.php and system will logs-out
this is how i do it :
//set timeout period in seconds
$idleTime= 60*2;
//check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout'])){
$session_life = time() - $_SESSION['timeout'];
if($session_life > $idleTime){
// your logout code here*
}
}
$_SESSION['timeout'] = time();
This makes $_SESSION['timeout'] reset every time a page is reloaded, i have this in an include file in the header of every sub page, works for me atleast.
The simplest way is this. Send the user to a log out page if they are not activating certain elements on your website
$secondsWait = 300; // these are seconds so it is 300s=5minutes
header("refresh:$secondsWait; logout.php");
contents for the redirect... logout.php, destroy any sessions and maybe also send a message alerting the user why they were logged out
<?php
session_start();
session_unset();
session_destroy();
?>

Categories