php中的会话超时无法正常工作,想知道我的错误是什么


Session Timeout in php not working fine, Like to know what is my mistake?

我正在使用PHP来解决会话超时。。。我找到了一些解决方案,所以我选择了一个我最了解的解决方案,那就是:

    $now = time(); // checking the time now when home page starts
    if($now > $_SESSION['expire'])
    {
    session_destroy();
    echo "Your session has expire ! <a href='login.php'>Login Here</a>";
    };

我还在我的登录处理器页面中添加了这个

$_SESSION['start'] = time(); // taking now logged in time
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60) ; // ending a session in 30 minutes from the starting time

from如何在30分钟后使PHP会话过期?

结果是消息Your session has expire ! <a href='login.php'>Login Here</a>确实出现了,但页面仍在主页中,而不是返回登录页面。。。我想知道在回显线下面添加header ('Location:login.php');是否会将其带回登录页面。。。

如何将回显消息更改为弹出消息,并将页面带回login.php?

谢谢。。。我知道网上有答案,但我想知道我的错误在哪里,这样我就可以在这里学到一些东西。。。非常感谢教学和指导

您不能在回显某些内容的同时使用header()调用重定向到主页。标头调用要求您不要回显任何内容。此外,弹出窗口需要使用某种客户端脚本(ECMAScript/JavaScript)。尝试在注销时输出此代码,而不是您的消息:

<script>
alert('Your session have expired! Please login again.');
location.href = 'login.php';
</script>

另一个解决方案是不要完全破坏会话。只需取消设置所有变量。然后在会话中存储一条错误消息,并重定向到登录页面。在登录页面上显示错误消息。类似这样的东西:

function my_session_destroy() {
  $_SESSION = array();
}
if (/* session expired  ...*/) {
  my_session_destroy();
  $_SESSION['error'] = 'Your session have expired. Please login and try again.';
  header('Location: login.php');
  exit(); //Always call exit() after a header('Location: ...') call!
}

login.php:

if(isset($_SESSION['error'])) {
  printf('<p class="error">%s</p>', $_SESSION['error']);
  unset($_SESSION['error']);
}