I make web with login/logout.
我用登录/注销制作网页。
If any link or button pressed on web I call ajax function to check login and if time expired logout user. In logout function I update my database.
如果在Web上按下任何链接或按钮,我会调用ajax函数来检查登录,如果时间已过期注销用户。在注销功能中,我更新了我的数据库。
But If I close browser or page user is not logged out and database is not updated. How can I add event listener for it.
但是如果我关闭浏览器或页面用户没有注销并且数据库没有更新。如何为其添加事件侦听器。
PHP FILE
if (isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch ($action) {
case "checkLogin":
echo isLogged();
break;
case "logout":
logout();
break;
//and more
}
}
function isLogged() {
$data = array(
"login" => 0,
"username" => "null"
);
if(isset($_SESSION["user"]) && isset($_SESSION["start"])) {
$session_start = $_SESSION["start"];
//more then 600 sec
if(time() - $session_start < 600){
$data = array(
"login" => 1,
"username" => $_SESSION["user"]
);
}else{
logout();
}
}
return json_encode($data);
}
function logout(){
if(isset($_SESSION["user"])) {
$connection = connectToDB();
if($connection != null) {
$nickname = $_SESSION["user"];
$time = date("Y-m-d H:i:s");
$sql_statement = "UPDATE users SET is_login='0',last_login='$time' WHERE username='$nickname';";
$connection->query($sql_statement);
}
session_destroy();
}
}
2 个解决方案
#1
0
There's no surefire way to "listen" for the user closing your window or, as @Taplar pointed out, powering off their computer. Using the technique of storing the login time within the session described in this question, you can run a cron or other kind of background task checking the database for sessions that are due to expire, and then expire them there.
对于关闭窗口的用户来说,没有万无一失的“倾听”,正如@Taplar指出的那样,关闭他们的计算机。使用在此问题中描述的会话中存储登录时间的技术,您可以运行cron或其他类型的后台任务,检查数据库中是否有到期的会话,然后在那里使它们到期。
#2
0
You can add unload listener with async - false, so browser will wait while request is not finished:
您可以使用async - false添加卸载侦听器,因此浏览器将在请求未完成时等待:
$(window).unload(function() {
$.ajax({
type: 'GET',
url: '/logout',
async: false
});
});
Note that browser will "hang" during request, and it can confuse user
请注意,浏览器在请求期间将“挂起”,并且可能会使用户感到困惑
#1
0
There's no surefire way to "listen" for the user closing your window or, as @Taplar pointed out, powering off their computer. Using the technique of storing the login time within the session described in this question, you can run a cron or other kind of background task checking the database for sessions that are due to expire, and then expire them there.
对于关闭窗口的用户来说,没有万无一失的“倾听”,正如@Taplar指出的那样,关闭他们的计算机。使用在此问题中描述的会话中存储登录时间的技术,您可以运行cron或其他类型的后台任务,检查数据库中是否有到期的会话,然后在那里使它们到期。
#2
0
You can add unload listener with async - false, so browser will wait while request is not finished:
您可以使用async - false添加卸载侦听器,因此浏览器将在请求未完成时等待:
$(window).unload(function() {
$.ajax({
type: 'GET',
url: '/logout',
async: false
});
});
Note that browser will "hang" during request, and it can confuse user
请注意,浏览器在请求期间将“挂起”,并且可能会使用户感到困惑