如何防止PHP代码在标头重定向后执行


How do I prevent PHP code executing after a header redirect?

我已经编写了一段代码来确定用户是否已登录,并且他们的会话是否已超时。如果他们没有登录或处于非活动状态,则会被发送到logout.php页面,该页面会更新数据库并销毁会话,然后将他们带回登录页面。

我遇到的问题是,在页面的后面是当用户提交表单时执行各种活动的代码。因为header()重定向实际上是页面上的第一个代码位,我希望服务器从上到下处理代码,所以如果我在表单上点击提交并因处于非活动状态而注销,那么当我重新登录时,我提交的更改就会发生。这种情况不应该发生。

代码:

//check if the userID has been set (is set at login)
if(isset($_SESSION['userID'])){
    //some code here to get variables from the DB
    //then check that the last recorded activity was not more than x minutes ago
    if(time() - $_SESSION['lastActivity'] < 1800){
        //update the $_SESSION['lastActivity'] variable
    } else {
        header('Location: logout.php'); //inactive, send to logout page
    }
} else {
    header('Location: logout.php'); //not logged in, send to logout page
}
if(isset some post variable){
    //update database
}

如果我没有登录或刷新页面的时间超过30分钟,则不应该运行最后一个if语句,但它确实运行了。有人能帮我解释为什么,以及如何预防吗?我的意思是,我知道我可以在if(isset($_SESSION['userID'])条件下包装整个后续代码,但这似乎很麻烦,第一个代码块肯定应该处理未正确登录的用户?

提前感谢

您应该有出口;在header()之后的下一行;

header("Location: ...");只向客户端发回一个标头,告诉它去哪里。它不会显式取消在服务器上执行当前脚本。

如果不希望脚本继续,则应始终在任何header("Location: ...");之后设置exit;