我希望用户在一段时间不活动后注销。我希望这个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代码一段时间后?
有很多拼错的单词。不好意思
根据您的需要修改代码。这段代码的作用是,如果用户在5秒内刷新页面,计时器将重置并再次开始计数。如果用户在5秒内没有刷新/重新加载页面,则会对控制器动作进行ajax调用以注销用户。向ajax调用返回一个新url,以自动将用户重定向到新页面。[仅供参考,我不喜欢自动下线,尤其是这么短的下线。当然,大多数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
}
});
}