Logging out after certain amount of time - php

What would the best way be to logout a user from a PHP application (so basically just perform a redirect) after X seconds of inactivity? For "inactivity" I'd count the time of the last page load, and if the current time is more than X seconds away, perform the redirect.
Is this something that would need to be achieved with Javascript?

You can use just html meta tag:
<meta http-equiv="refresh" content="1000;url=buy.aspx">
put it in head
where 1000 is a time in sec and url is an url to redirect.

Just answered this question yesterday... the OP wanted to ask after certain amount of time, it the user would like to stay logged in or not.
For a plain redirect without any confirmation, you can use a simple setTimeout call:
var minutes = 30;
setTimeout(function(){location.href = 'logout.php';}, minutes*60*1000);

Do you really want a redirect for some reason?
Usually each user session has an associated timestamp. You then make sure the session hasn't expired for the user, or ask them to log in. So in effect, you're just making sure sessions are valid.
If you redirect someone to a logout page, you really are not achieving anything. You will also need to make sure the session has not timed out server side. Anything that is client side, including redirects to a logout page, is unreliable, and can be circumvented.
The simplest form in PHP:
<?php
session_start();
$session_lifetime = 60*60; // 1 hour
if (!isset($_SESSION['time']) || !$_SESSION['time']) {
$_SESSION['time'] = time();
}
if (time() - $_SESSION['time'] > $session_lifetime) {
// session has expired
$_SESSION['user'] = null;
$_SESSION['time'] = null;
} else {
// keep session alive
$_SESSION['time'] = time();
}

What if the user starts typing in the form on the page and hasn't finished by your time out period? I handle inactivity in another way than described in other answers so far.
var rowLockSeconds = 0;
function startRowLockTimer()
{
setInterval("incrementRowLockTimer()",60000);
$("input").keypress(function (e) { rowLockSeconds=0; }).click( function() { rowLockSeconds=0; });
$("textarea").keypress(function (e) { rowLockSeconds=0; }).click( function() { rowLockSeconds=0; ; });
window.onbeforeunload = function obul() { if (hasChanged) { return 'You will lose any unsaved changes you\'ve made.'; } }
window.onunload = clearRowLock;
}
So as they've logged in, the row lock timer starts at 0. Every 60 seconds it calls the interval function to see if it has timed out.
function incrementRowLockTimer()
{
rowLockSeconds = rowLockSeconds+60;
// 10 minute timer to clear someone out of a page if there has been no activity
if (rowLockSeconds >= 600)
{
window.onbeforeunload=null;
// clear rowLock with request here
$.get('../ajax/rowLock-server.php?do=delete&rowLockID='+currentRowLockID+'&userUUID='+currentUserUUID, function() {
alert('You have been logged out of this page after 10 minutes of inactivity.');
document.location.href='../main.php';
});
}
}
The AJAX controls clear out the DB row lock.
The key is the input and textarea bindings so that if the user types anything into the form, the timeout is reset and they have another 10 minutes.

Related

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.

Automatic Logout in PHP upon inactivity only

I already had some research and i found a functional code to logout upon inactivity, but my problem is i still need to refresh my browser inorder to prompt my alert function to be able to logout it. I want a code function that will automatically log you out even if you won't do anything. BTW this is my code.
<?php
if (time() - $_SESSION['timestamp'] > 30) {
?>
<script type="text/javascript">
alert("You Have Been inactive for 30 seconds");
window.location.href = "logout.php"; //To my logout function
</script>
<?php
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}
?>
pretty easy.
if you have a file that you include in each page you can implement it by adding the refresh script eg
header("Refresh: 1200; url = logoutsess.php");
this will redirect to a file logoutsess.php after 20mins therefore killing the session
It's not possible without refreshing, at least not with PHP.
Have you considered the use of AJAX for this instead of refreshing the browser every 30 seconds.
xhr requests verify_session.php and verify_session.php will check if the user has done anything within the last 30 seconds and print 1 or 0, your JavaScript will then redirect the browser to logout.php if it detects 0.

Knowing real time an user is in my site

I have a website, and I have to implement (with PHP and/or JavaScript) an alert message that triggers two minutes after a visitor has entered the site. I've searched, but all solutions I've found are for an unique page. I need the timer counter to start when the user enters my site, no matter through which page. And I need that counter keeps counting while the user navigates my site's pages.
One solution could be using session variables. I can make a script that looks for this variable, if it doesn't exist means that the user is entering the site. Then I set this variable with current time. The script it's in each page, and it will be reading this variable via AJAX each x seconds and I'll know when the user is in my site since two minutes.
I don't know if it's right or not (I've not implemented yet), but I'm not pretty sure if session is the best way. If the user leaves the page but has other navigator windows opened, the session doesn't expire, and if he enters the site again, the counter will not be reset.
So, two questions:
Is there a better method to have
more control on the real entering
and exiting?
If not, is my above
approach right?
Thanks.
Something like this should work.
$alert_message = false;
if(!isset($_SESSION['time_entered'])){
$_SESSION['time_entered'] = time();
}
if($_SESSION['time_entered'] =< time() - 120){
if(!isset($_SESSION['message_sent'])){
$alert_message = true;
$_SESSION['message_sent'] = true;
}
}
And in <head>:
<?php if($alert_message):?>
<script type="text/javascript">alert("You've been here for at least two minutes.");</script>
<?php endif;?>
Also make sure that you have session_start() at the top of every script.
You don't need AJAX, you just need to store the time in a session variable, and then include some JavaScript on each page, here is an example:
<?php
session_start();
$time = microtime(true);
if (!$_SESSION['foo']) {
$_SESSION['foo'] = (microtime(true)+120);
}
?>
<script type="text/javascript">
var timeoutID = setTimeout(function() {
alert('two minutes have passed');
}, <?php echo bcsub($_SESSION['foo'], $time)*1000 ?>);
</script>
You will need some additional logic so that it does not keep firing after the 120 seconds are up.

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

Automatically re-direct a user when session Times out or goes idle

I want to have a timer going to run every 3 minutes on the page (javascript), to detect if a php session ($_SESSION) has timed out... and if so, redirect them automatically.
A good example would be, a user logs in and runs up stairs, and never comes back down... I want the javascript to log them out with a simple redirect...
Is this possible? and how would I do such a thing? I am using PHP and JavaScript.
What Rob Kennedy said below is exactly what I am looking for:
...when the session times out,
the browser should be told to navigate away from the current page.
Some banks do this after a period of inactivity, for example.
You could use a simple meta refresh:
<meta http-equiv="refresh" content="180;url=http://example.com/logout" />
Or you implement a timeout with PHP:
session_start();
if (isset($_SESSION['LAST_REQUEST_TIME'])) {
if (time() - $_SESSION['LAST_REQUEST_TIME'] > 180) {
// session timed out, last request is longer than 3 minutes ago
$_SESSION = array();
session_destroy();
}
}
$_SESSION['LAST_REQUEST_TIME'] = time();
Then you don’t need to check every 3 minutes if the session is still valid.
New and improved solution
As mr kennedy pointed out my original solution (below) doesn't work. so here is a way to do it.
In the user database keep a last-activity timestamp that updates every time a user loads a page.
Then in a checkaccess.php
if ( time-last_access > max_inactivity_time ) {
return array('access' => '0');
}
else {
return array('access' => '0');
}
Call checkaccess.php in the javascript timer(below) and logout accordingly
This also allows for a "currently logged in users" function
thanks mr kennedy
Original, non-working solution
Create a php page that returns 1 or 0 based on the validity of the current users session
Then in your pages that you want to timeout add this to the head (you need jquery)
setInterval(function(){
var url = UrL_OF_SESSION_CHECKING_PAGE;
$.getJSON( url,
function( data ) {
if (data.access=='0') {
window.location = LOGIN_PAGE;
}
}
);
}, 180000);
Every 180 seconds (3 minutes) it requests the php page and gets the validity of the session. If its invalid it redirects to a login page
If the user has multiple pages open the pages will timeout and redirect at different times because their timers are different.
Here's a good page on javscript timers
http://ejohn.org/blog/how-javascript-timers-work/
Simple session checking page
session_start();
die(
json_encode(
isset( $_SESSION['VARIABLE'] ) ? array( 'access' => '1') : array( 'access' => '0' )
)
);
change VARIABLE to one of your session variables
If you want this to happen before the page is even refreshed, you'll want periodic ajax calls. You can use jQuery Heartbeat to make calls every 3 minutes, and use one of the PHP methods already provided by other users to check the session

Categories