简体   繁体   English

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

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

I've written a block of code to determine whether a user is logged in and their session has not timed out.我编写了一段代码来确定用户是否已登录以及他们的会话是否超时。 If they are not logged in or they have been inactive they get sent to the logout.php page which updates the DB and destroys the session, and then bumps them back to the login page.如果他们没有登录或者他们一直处于非活动状态,他们会被发送到 logout.php 页面,该页面更新数据库并破坏会话,然后将他们撞回登录页面。

The issue I have is, further down the page is code to carry out various activities when a user submits forms.我的问题是,当用户提交表单时,页面下方是执行各种活动的代码。 Because the header() redirect is virtually the first bit of code on the page and I expect the server to work through the code from top to bottom, it boggles my mind a bit that if I hit submit on a form and get logged out because I have been inactive, when I log back in the changes I submitted are made.因为 header() 重定向实际上是页面上的第一个代码,我希望服务器从上到下处理这些代码,如果我在表单上点击提交并被注销,这让我有点困惑,因为我一直处于非活动状态,当我重新登录时,我提交的更改已完成。 That should not happen.那不应该发生。

Code:代码:

//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
}

This last if statement should not run if I am not logged in or haven't refreshed the page in more than 30minutes, but it does.如果我没有登录或在 30 分钟内没有刷新页面,最后一个 if 语句不应该运行,但它确实如此。 Can anyone help me with why, and how to prevent it?任何人都可以帮助我解释原因以及如何防止它? I mean I know I can wrap the entirety of subsequent code within the if(isset($_SESSION['userID'])) condition, but that seems cumbersome and surely the first code block should be dealing with users not properly logged in?我的意思是我知道我可以将整个后续代码包装在 if(isset($_SESSION['userID'])) 条件中,但这看起来很麻烦,而且肯定第一个代码块应该处理未正确登录的用户?

Thanks in advance提前致谢

You should have exit;你应该有退出; on the next line after the header();header()之后的下一行

header("Location: ..."); only sends a header back to the client, telling it where to go.只向客户端发送一个标头,告诉它去哪里。 It does not explicitly cancel the execution of the current script on the server.它不会明确取消服务器上当前脚本的执行。

You should always have exit;你应该总是有exit; after any header("Location: ...");在任何header("Location: ..."); if you do not wish the script to continue.如果您不希望脚本继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM