Logout a user after certain time - php

I'm currently storing a timestamp of the users last activity in my database in which if that hasn't been updated for 15 minutes (for testing doing 2 minutes) I want it to log the user out.
I have been trying different things but they all seem to log me out even though they shouldn't be.
Example of something I've tried
$Online = time() - 120;
if ($CheckOnline['lastaction'] < $Online){
header("Location: Logout.php");
session_destroy();
}
Am I going at this the wrong way.? If I do $Online < $CheckOnline['lastaction'] it keeps me logged in but never logs me out.
Thank you in advance!

Supposing the 'lastaction' is in epoch time format, this would be quite easy. You can check by the current time minus the last action time, that will give you the time in-between the actions. You can do something like this:
$maxTimeAllowed = 120; // 2 Mins
if ((time() - $CheckOnline['lastaction']) > $maxTimeAllowed){
session_start();
session_destroy();
header("Location: Logout.php");
}
I should also mention, in order for you to destory a session you must start it first, but I figure you would handle that logic either in your logout.php or on the page this will be run on, but i've included it just incase.
Another alternative is via javascript.
setTimeout(() => {
window.location = 'logout.php'
}, 120000) // 120000 because JS counts in milliseconds
That way, this will ensure that no matter what the user will be logged out in 2m, not just when they make another request.
Sidenote: If the date/time in your database is stored not as epoch time, it might be worth using strtotime() to convert them, as epoch time is much easier to work with.

Related

How to set session life time

Is there any way to set the life time on a specific session. For
example let's say that I have 2 session:
$_SESSION['A']='1'
$_SESSION['B']='2'
I want, for example, change the life time on the session A, on 60s. Could I do this without using cookies (For avoid user manipulation)?
you could do like this to control particular session
$_SESSION['first_session']="10";
$now = time();
if (isset($_SESSION['destroy_session']) && $now > $_SESSION['destroy_session']) {
session_unset($_SESSION['first_session']);
}
$_SESSION['destroy_session'] = $now + 10; //10 secs
echo $_SESSION['first_session'];
after 10 seconds your session will get empty.
Server side information should constantly deleted.
For set life time session in php, you can use the function session_set_cookie_params, before the session_start.
session_set_cookie_params(3600,"/");
session_start();

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.

Protect download path with PHP Sessions/Cookies?

I need to ensure that a person has been to, and filled out, a registration form before going to the product download page. Right now I submit the form via ajax and if the returned JSON = success I redirect to the appropriate download page accordingly. I would like to protect the download page from direct access, to ensure we capture the lead first. I know that PHP sessions and cookies can be manipulated but it fits our needs, I am aware of the consequences etc and just need to make this work.
So on page 'http://www.example/register.php' I want to set and hash a cookie based on the current time:
<php
$time = ('Y-m-d H:i:s');
//set a new cookie with this value and hash it
?>
Then on http://www.example.com/download.php check for the cookie, if it is set AND set within the last hour display the download content, if it isn't set or has expired, redirect back to the register page
<php
if !$cookie or expred {
location('http://www.example.com/register.php');
die();
} else {
//download content
}
?>
I know this example is very rudementary, but I could use some help getting on the right path. I apprecite it!
You will need to use session_start() at the top of each page, without this you cannot read or write any session data.
Once you have done this, you will change session variables in the $_SESSION global. To set the time try $_SESSION['time'] = time(). This will save the current time in seconds (Unix Timestamp). To calculate if the time was set greater than an hour ago use this:
session_start();
// 60 seconds * 60 minutes = 3600, or 3600 = seconds in an hour
if(time() - $_SESSION['time'] > 3600) {
// Current time - survey_time is greater than one hour (expired)
header('Location: /survey/page/url/');
} else {
// Not expired - do stuff
}
Let me know if you have any questions!

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);

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