我尝试在用户处于非活动状态10秒或更长时间后在我的php应用程序中实现自动注销。我的代码一切正常,唯一的问题是,要进行注销,用户必须再次点击屏幕。我希望自动发出警报消息和注销,无需任何点击。这是我的代码片段:
if (isset($_SESSION['last_action']))
{
//Figure out how many seconds have passed
//since the user was last active.
$secondsInactive = time() - $_SESSION['last_action'];
//Convert our minutes into seconds.
$expireAfterSeconds = 10;
//Check to see if they have been inactive for too long.
if($secondsInactive >= $expireAfterSeconds){
//User has been inactive for too long.
//Kill their session.
echo "<script>
alert('You have been logged out');
window.location.href='../clinician/logout.php';
</script>";
}
}
答案 0 :(得分:2)
您需要做的就是调用函数在javascript中间隔运行
<script language='javascript'>
var timeout = 10 * 1000; // 10 seconds
var lastAction = <?php echo isset($_SESSION['last_action']) ? $_SESSION['last_action'] : time();?>;
setInterval(function(){
var now = new Date();
if (typeof lastAction !=='undefined' ){
if(now.getTime() - lastAction >= timeout ){
alert('You have been logged out');
window.location.href='../clinician/logout.php';
}
}
}, 1000) // repeat every 1 second;
</script>
和optionaly你可以将你的间隔设置为10000(10秒),不需要经常检查。一旦达到10秒,就会退出。
但我认为如果用户移动他们的鼠标或点击某些东西,它将不会将它们记录下来,因为它们在页面上处于活动状态。如果是这样,在setInterval函数之后,你可以添加,
<script language='javascript'>
var timeout = 10 * 1000; // 10 seconds
var lastAction = <?php echo isset($_SESSION['last_action']) ? $_SESSION['last_action'] : time();?>;
var timer = function(){
return setInterval(function(){
var now = new Date();
if (typeof lastAction !=='undefined' ){
if(now.getTime() - lastAction >= timeout ){
alert('You have been logged out');
window.location.href='../clinician/logout.php';
}
}
}, 1000) // repeat every 1 second;
}
window.onmousemove = function(e){
clearInterval(timer);
timer();
}
window.onclick= function(e){
clearInterval(timer);
timer();
}
// and make initial call
timer();
</script>