在会话超时触发之前显示消息

时间:2017-04-09 19:08:05

标签: php

我有一个php网页,可以在10秒钟不活动后将用户注销。 10秒后,我需要在重定向到主index.php页面之前点击刷新按钮。如何使弹出框显示"由于不活动而退出"然后它重定向到index.php而不刷新? P / S:我是一名学习基础知识的学生,所以我不太了解。

session_start();

$timeout = 10;
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
// See if the number of seconds since the last
// visit is larger than the timeout period.
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
// Destroy the session and restart it.
session_destroy();
session_start();
}
}

So I tried something like this using alert.Why doesn't it work?
<?php
//include ("popup.php");
session_start();

$timeout = 10;
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
// See if the number of seconds since the last
// visit is larger than the timeout period.
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
echo"<script type='javascript'>alert('10 seconds over!');
header("location:../../index.php");
</script>";

}
// Destroy the session and restart it.
session_destroy();
session_start();
header("location:../../index.php");
}


// Update the timout field with the current time.
$_SESSION['timeout'] = time();

1 个答案:

答案 0 :(得分:0)

  1. 使用Javascript实现弹出窗口;或
  2. 在条件中,使用header("Location: logout-notice.php");
  3. 编辑: 我现在无法测试,但根据您的更新,我看到的是您正在检查$ _SESSION ['timeout']但我没有看到它在任何地方声明或给出值。您在顶部设置了$ timeout的变量,但它们是不同的变量。

    也许是这样的:

    $_SESSION['timeout'] = time() + $timeout; // should = 1491838370 if set at UNIX time of 1491838360
    if(time() > $_SESSION['timeout']){ // evaluated at 1491838380 which is > 1491838370 results in true
        ?> 
        <script type='javascript'>alert('10 seconds over!');</script>
        <?php
        header("Location: ../../index.php");
    }
    

    问题在于您将在何处/如何评估此问题。如果您希望每个用户的操作验证它们是否已处于活动状态,则可以在每个文件的开头包含此脚本。不利的一面是,如果他们暂时不活动,那么在他们做某事之前不会评估。

    您可以使用依赖于SetIntervalSetTimeout的纯javascript版本来评估每十秒钟,并使用window.location.href弹出一个警报,同时注册到index.php。这样的事情(再次你可能需要调整,这是未经测试的):

    var checkSession = setInterval(
         function({
             var sessionExpires = <?=$_SESSION['timeout']?>; //this is probably considered heresy, but as long as the javascript is evaluated by the PHP processor, it should work
             var currentTime = Math.floor((new Date).getTime()/1000);
             if(currentTime > sessionExpires ){
                  alert("Take your stuff and go!");
                  window.location.href = "../../index.php";
             }
         }, 10000);