Reputation: 1321
I have created a Login page, amongst many others pages, which contains code to check the session. If the user doesn't have a session then all pages will reload and redirect to the logout page. This script is called every three seconds.
The code I've written is working fine but I want implement it another way. When the user logs out, all open tabs reload/refresh causing the user to be logged out. Is that possible?
sessioncheck.php:
<?php
session_start();
if(isset($_SESSION['username']) && $_SESSION['username'] != ''){
echo "true";
}
else {
echo "false";
}
?>
This code is in every page footer:
<script>
function gettatus(){
$.get("sessioncheck.php", function(data){
if(!data) {
window.location = "logout.php";
}
setTimeout(function(){
checkLoginStatus();
}, 3000);
});
}
$(document).ready(function(){
gettatus();
});
</script>
Upvotes: 45
Views: 46333
Reputation: 11
Ajax requests frequently to server to check whether the user is still logged in or not. But this will make a huge server load and also consume network bandwidth of user
the load to the server disables this option. I've tested it.
Upvotes: 0
Reputation: 3238
lets consider somethings that you are using php session and you are checking following code every time you are loading your pages or after some time duration
<?php
session_start();
if(isset($_SESSION['username']) && $_SESSION['username'] != '')
echo true;
else
echo false;
?>
So on your logout.php file you are probably doing something like this unset($_SESSION['username']); and session_destroy();
Therefore when your page will call that checking php you will find false in return and that following user will no longer get access from any browser and any pages. And For automatically logout try this
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_destroy();
unset($_SESSION['username']);
echo false;
Note: you must set
$inactive = 6000;
(for example) as global variable while login
Upvotes: 1
Reputation: 11340
When ajax is useful
Making an ajax request to your server every 3 seconds is useful just in case 1. you have opened tabs in different browsers 2. or in many computers. 3. or you use very old browsers
Setting cookie doesn't work.
Approach using setting cookie doesn't work since one tab is not aware of changed cookies in another tab. That's because of document
(where cookies are got from with getCookie) of tab A is not changing without request to a server. You can open two tabs of SO and try to set setCookie('name', 'val', 1)
in one tab and look at document.cookie
in the other tab.
How to make another tabs knew about logout immediately
If you need to logout all tabs of the same browser, it would be great to pass signals between tabs. There are a couple of methods, I want to tell you about using localStorage
(demo here).
You can attach a listener to a storage
event (fired when storage item is changed) and send a logout-event
signal.
localStorage.setItem('logout-event', 'logout' + Math.random());
Every other tab will get it with a listener.
window.addEventListener('storage', function(event){
if (event.key == 'logout-event') {
// ..
}
});
What if old browsers without localStorage
You can use both approaches - localStorage
and auto-refresh, for example every 60 seconds, just to be sure it works when tabs are opened at different computers. If localStorage
doesn't work (very old browsers), auto-refresh every 3 seconds.
The following fiddle shows how to deal with it.
What else?
You can use node.js + socket.io to send signals between all browsers of a user. It works rapidly and will logout a user on every device, but it is a little harder to deal with than a common jQuery.
Upvotes: 113
Reputation: 12478
Here is what you need. In this, snippet shows some error I dont know why. So, please copy the javascript code to browser console(f12) and check it. It works When user login, you must use
setCookie('loggedin','true',1);
Here we are setting a cookie called logged in
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var startPos = document.cookie.indexOf(name);
if(startPos == -1) return null;
startPos+=(name.length);
if(document.cookie.indexOf(";",startPos) == -1){
return document.cookie.substring(startPos,document.cookie.length);
}
else{
return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos));
}
return null;
}
function checkCookie() {
var loggedin = getCookie("loggedin");
if (loggedin && loggedin !=null) {
// Logged in
//do nothing
}
else{
window.location.href="login.php";
}
}
<!-- use the below code in logged in home page to check whether the user is logged in still or not in a time interval of 1 second. Change 1000 as per your need.//-->
<body onload = "setTimeout(checkCookie,1000);">
Upvotes: 0
Reputation: 12478
For this, you have two choices. Either store the session values in server and make Ajax requests frequently to server to check whether the user is still logged in or not. But this will make a huge server load and also consume network bandwidth of user. Or else,
check the logged in cookie still exists or not in browser frequently. This will be the good approach.
Both can be performed by setTimeout
or setInterval
But the second one should be good.
Upvotes: 0