I am working on a website hwere i need to introduce security for reasons, my website automatically signs users out after 10 minutes of inactivity. The behavior is, at about 8 minutes of inactivity, a jquery ui dialog pops up, warning the user of their impending timeout. The user can choose to stay signed in, sign out now, or do nothing and they are forced to sign out at the end of the 10 minutes. I achieve this through a javascript code snippet that timeouts (no mouse/keyboard event) and reset any time the user does what I consider an "activity".
My problem is i can make this thing run for my single webpage but have no clue how to use this for complete domain. I have thought of cookies to achieve this feat as well but not very sure. If someone can suggest me what approaches i shall follow for my task, it will be great possi. bly with code example
Get this timeout script running on my complete domain rather than a single webpage. Possibly using cookies or something else.
I would recommend against javascript and create a complete PHP solution.
This can be achieved simply by giving a user a cookie that expires after 10 minutes on each PHP page. That way, the cookie is renewed with each visit, and if they come back after that ten minutes, the cookie is gone and the system will no longer recognize them.
I would also suggest against sessions, they can get messy easily, and if you want to expand to multiple machines to load balance, it becomes almost impossible to manage. It's not a realistic production tool.
Call this every page - This will check if they already have a cookie, if they do, it will renew it with the same value for ten minutes (60 seconds times ten minutes). You can change the cookie name of 'user' to whatever you want.
if(isset($_COOKIE['user'])){
setcookie('user', $_COOKIE['user'], time()+60*10);
//put your user validation code here to make sure the cookie is real
//then you can put your logged in specific data under it.
}
To authorize a user in the first place, most likely when they login, you can do this:
setcookie('user', $value, time()+60*10);
And if you want to log someone out, you can do this:
setcookie('user', '', 0);
Best of luck!
You can use session and/or cookies for this matter. The way you use them, is that in every page of your website you first check for the cookie/session, and only then proceed. So if your user is logged out once, and attempts to go to another page on the website, he/she will first have to login and only then he can proceed, since the session is no longer available for that user.
Something of this sort -
<?php
if( $this->session->userdata('logged_in') == FALSE )
{
// Login again
}
else
{
// Display the page
}
?>
You can do this by setting their session cookie to expire after 10 minutes. Use session_set_cookie_params() to set the duration of the cookie (first parameter).
session_set_cookie_params(600, '/', 'www.example.com', false, false);
session_start();
Make sure you call it before session_start().
You would then use JavaScript to check the expires parameter of the cookie. If it is getting close to the expired time you then would use that same JavaScript to show them the dialog warning their session is about to expire
Related
I have a requirement that after closing the browser when user open site it should ask for login by default.
I destroyed the session values on logout button so when user clicked on logout button it works fine but if user directly close the browser or tab the session are not destroying.
I have also tried to set session.cookie_lifetime value to 0 but its not working.
The best way to do this in my opinion is the store the session with the time in it, you can create a javascript heart beat which will keep the time updated every x seconds and as look as now is never a larger time than time+x seconds then you will have your heart beat. If the time surpasses it the session will time out and you're off the the races.
On login:
session_start();
$_SESSION['last_action'] = time();
An ajax call every few (eg 20) seconds:
windows.setInterval(keepAliveCall, 20000);
Server side keepalive.php:
session_start();
$_SESSION['last_action'] = time();
On every other action:
session_start();
if ($_SESSION['last_action'] < time() - 30 /* be a little tolerant here */) {
// destroy the session and quit
}
Browsers are an implementation of web standards. They have differences between them as to how they choose they decide to implement them and can sometimes differ from the standard.
If you set a session/temporary cookie, the idea should be that it will be deleted as soon as the website is closed. However, browsers don’t always follow this as gospel. They have convenience features which can keep the cookies and restore the user's session. This could be useful if the browser suddenly crashed or a user accidentally shut down the tab.
On the other hand, for developers, this creates meddling which is not how they should behave. This isn’t the sort of thing that can be controlled so you can’t really delete a cookie when a tab is closed. The only way to solve it is to store a timestamp in a session or another cookie and anytime a page is loaded, check to see if a reasonable timestamp has passed, after which case, the cookie could be destroyed. It’s not an ideal solution, but it is the only way to implement it in modern browsers.
I have a problem with logged in users closing their browsers.
My code can't run due to the browser closing and so their logonstatus cant update to 'N' in the database. Also due to the session being destroyed they cant go back to the main pages as I have this code if (!isset($_SESSION['logged in'])) { etc to prevent people from viewing any pages without logging in.
When a user logs on their logonstatus changes to 'Y' and I record the time they logged in.
I record their lastactivity time on each page load.
I redirect users to the login page and change their logonstatus if they have been idle for 20 min on a page.
I also have a cron job due to the browser close issue which runs every 5 minutes and checks if the users last activity has been longer than 20 min and if so their logonstatus becomes 'N'
I think users having to wait 20+ min to re-login due to browser close is too long and so I would like to make it possible to login in again straight away.
I have read about the unload functions of javascript but apparently it is unreliable.
Is there any other way I could go about this?
Closing the browser is always a client side action. So you will need javascript to send the action to the server for PHP to do something.
You can use onbeforeunload to send something to the server, but it is indeed unreliable. A more reliable method is to make the session time a lot shorter (eg: 2min) and then have an ajax call every 30seconds to the server to keep the session alive (make sure its a page with a very small impact on server/connection). If the request fails 4 times, the session is destroyed. Now your cronjob can run every 2mins and a user only has to wait that long.
Another approach is to store a cookie on the users computer with a GUID and save it in the database with the "Logged ='Y'". Now when somebody tries to log in to an account which is already logged in, check if its the same user (cookie) and if so, allow it.
This still makes it possible for one user to log in twice, just harder and not by mistake.
You need to change the duration of your session cookies so that they last as long as the browser window remains open; do this with session_set_cookie_params, setting the lifetime to 0. Don't forget to make sure that your cron script and PHP's session gc max lifetime don't delete sessions before 20 minutes have passed.
Since you keep a record of their last access time and check it on each request, you can continue to log out people after 20 minutes of inactivity (just destroy their session and redirect to the login page).
I'm keeping track of the time that users are logged in. After they close the whole browser they are logged out; but when they only close the tab (there's only one tab), and navigate back to the website within a few minutes they are logged in again.
Someone told me that this behavior can be changed in the server configuration. Does anyone know how?
I'm using PHP 5.2 and Apache. Just a normal webserver. I'm also using the Kohana 3 PHP framework. For logging users in there's being a session set with a cookie, in the cookie there's a session id.
Thanks!
You cannot reliably find out when the user closes your page - unload-related events also trigger when navigating to another subpage on your side.
So the most common solution is to simply make a session time out after x minutes of inactivity.
Additionally, if you set your session (id) cookies without an expiry time ("session cookies") they will be deleted when the browser is closed.
By the way, a not really good "solution" for your request would be setting the session expiry time to a very very low value (30 seconds) maybe and "refresh" the session through an AJAX request in the background every ~15-20 seconds. However, if someone's connection is very slow the request might arrive too late and besides that, this solution would cause lots of unnecessary traffic.
I would like to store the login, logout and duration time in database.
The login time is created when the user is authenticated(successfully logged in)
The logout time is created when the user clicks the logout button
The duration is logout - login time. (logout minus login)
But the problem is, what if the user didnt click the logout button. Here are the situations:
Internet loss
Close the browser/tab. (I need this must use javascript, but i donnu how to do it, any idea?)
EDIT:
I forgot to add something to the question, the program is a full flash program, there is no navigation to other page. Only 1 page
It's important to remember that all session/log-in functions in PHP are usually cookie based. So, changing the lifetime of the session cookie should solve your problem:
http://us3.php.net/manual/en/function.session-set-cookie-params.php
Also, you can set the PHP sessions so they only use cookies:
http://us2.php.net/manual/en/session.configuration.php#ini.session.use-only-cookies
Again, you can catch the browser window / tab close but ... why? For instance I may have your site open in multiple tabs. If I close one of those tabs should I automatically be logged out of your website? That's a very bad design. Instead, set the session lifetime so it expires if the browser is closed and not just a tab. (Note also that window.unload will logout when any window on your site that closes - including a pop-up or an iframe. Do you really want that?)
http://us2.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime
If you want to store session state in a database try any one of these guides. Or, roll your own with session_set_save_handler
You can't rely on receiving an event for the user logging out, if they simply close their browser, or disappear from the internet.
In this case you'll have to have a session timeout of some kind, and record the logout when your app realises their session is too old.
If this is a real requirement, then I'd say you need a "cron" job monitoring the sessions for timeout. When a session has timed out, if the were logged on, it then records a "logout" event for that user.
Note that you can't use (for example) ASPNET's Session_End event, because that won't be reliably called either (for example if the server process restarts).
Another option is to add the logout time next time that user logs on - when they log on, you check for old sessions and assume that any which weren't closed lasted for a fixed amount of time since the last page hit.
That's really all you can do.
Regarding the closing of browser/tab, you can bind the unload event (window.onunload, jQuery's $(window).unload(fn), or any other) to notify your server. A more general purpose solution would be to periodically ping your server (say, every 5 min), but it might be annoying to the user, so do so judiciously.
I have a web app game and while in the game I want to have it so if a user closes the page or their browser, it will automatically log them out. I tried using the onbeforeunload event attached to the window:
window.onbeforeunload = function() {
// perform logout functions here
}
The problem is, that will also fire if the user refreshes the page. Is there a way I could detect whether or not the user is completely closing the whole page, or just refreshing it?
There is not a detectable difference. To automatically logout a user, you should set an expiration on your cookie storing the login or session information. So if you set it for 1 hour, the user would essentially be logged out after that time since the cookie would be destroyed. If you wanted to postpone this auto logout while they are still interacting with the site, you could reset the expiration of the cookie every time they perform some sort of action (clicking a link, activating an AJAX call, etc). That would mean that they'd be logged out after 1 hour of inactivity as opposed to just 1 hour from login, which sounds more like what you want.
If you set the cookie's expiration to 0, then it will expire it after the session ends. That usually occurs when the user quits their browser entirely. That's another option as well.
As said, you cannot. Even worse, this event have been abandoned by lot of browsers, probably because it have been abused by malicious scripts doing pop-under and such.
A possible workaround is to have an Ajax script "phoning home": if it is silent for some time, the user just abandoned the site (closed page or browser).
Have the onunload event send a request to the server which will cause the session to expire in n seconds (where n is the maximum time for a page reload request to occur, so perhaps 10). Then have the script for the site check to see if that event is scheduled and if so, cancel it. This would give you the behavior you seem to want.
But yeah, I'd recommend simply having the session expire.
If I'm not mistaken Javascript should have a function named something like onWindowClose, maybe try searching for it?
Regarding PHP solutions, I'm not sure if there are any but I suggest you take a quick look into PHP Connection Handling, specifically the connection_aborted() and register_shutdown_function() functions.