我希望用户在一段时间不活动后退出。我想这个PHP代码在用户不活动一段时间后自动运行。它必须在不刷新页面的情况下发生。
<?php
if (isset($_SESSION['user_login_status'])) {
$max_time = 5; // Maximun inactive time(this time is set in seconds )
$current = time(); // Current time on server
if (!isset($_SESSION['Inactive']))
{ // Create session inactive;
Session::set('Inactive', time()); // Create session inactive;
} else {
$session_life = $current - $_SESSION['Inactive'] ;
if ($session_life > $max_time )
{
Session::destroy(); // This is a function that destroys all sessions and logging out the user
header('location: index.php'); // Redirects to some kinda page
} else {
$_SESSION['Inactive'] = time();
}
}
}
?>
此PHP代码正常工作,用户在刷新页面5秒后注销。但我需要在这5秒不活动后运行此代码,它应该重定向到另一个页面。我尝试了一些ajax代码,但它没有用。
任何建议如何在一段时间后运行该PHP代码?
很多拼写错误的单词。对不起。
答案 0 :(得分:1)
根据您的需要修改代码。这段代码的作用是,如果用户在5秒内刷新页面,计时器将重置并再次开始计数。如果用户未在5秒内刷新/重新加载页面,则会对您的控制器操作进行ajax调用以关闭用户。将新url返回到ajax调用以自动将用户重定向到新页面。 [仅供参考,我不喜欢自动注销,特别是这么短的注销。当然,大多数Web服务器都有会话超时。我宁愿选择那些超时。]
// add these functions at the bottom of the output html page within <script> tags
// YOU SHOULD CALL setLogoutTimer FUNCTION ON MOUSEMOVE OR SOME USER ACTIVITY EVENT.
// otherwise user will be logged out even when the user is doing something on the page
setLogoutTimer();
function setLogoutTimer() {
var myTimeout;
if (window.sessionStorage) {
myTimeout = sessionStorage.timeoutVar;
if (myTimeout) {
clearTimeout(myTimeout);
}
}
myTimeout = setTimeout(function () { logoutNow(); }, 5000); //adjust the time.
if (window.sessionStorage) {
sessionStorage.timeoutVar = myTimeout;
}
}
function logoutNow() {
if (window.sessionStorage) {
sessionStorage.timeoutVar = null;
}
//MAKE AN AJAX CALL HERE THAT WILL CALL YOUR FUNCTION IN
// CONTROLLER AND RETURN A URL TO ANOTHER PAGE
$.ajax({
url: 'YOUR CONTROLLER ACTION URL',
cache: false,
async:false,
type: 'POST',
success: function (msg) {
window.location.href=msg; //msg is the url of another page returned by the controller
}
});
}