当 header(Location: xxx) 在里面时 PHP if 语句被忽略

2022-01-11 00:00:00 if-statement header redirect php

我有一个奇怪的问题.我的页面顶部有一个 if 语句,当 header(location: xxx) 命令在其中时,它似乎被忽略了.

I have a strange problem. There is an if-statement at the top of my page that seems to be ignored when a header(location: xxx) commmand is inside of it.

$check = $authorisation->check(); 
// i know this results in true by echoing the value 
// (you've got to believe me on this one)

if(!$check){
    // redirect to message
    header("Location: message.php");
    exit;

}else{
    // do nothing, continue with page
}

无论 $authorisation->check() 的结果如何,这总是重定向到 message.php 页面!

This ALWAYS redirects to the message.php page, no matter what the outcome of $authorisation->check() is!

奇怪的是,当我注释掉 header-command 并将 echo 放在 if 语句中进行验证时,一切都按预期工作:

Strange thing is, when I comment out the header-command, and put echo's in the if-statement for verification, all works as to be expected:

    $check = $authorisation->check(); // true
    if(!$check){
        // redirect to message
        echo "you are not welcome here";
    }else{
        echo "you may enter";
    }

结果是你可以进入";

这也可以按预期工作:

    $check = true;
    if(!$check){
        // redirect to message
        header("Location: message.php");
        exit;

    }else{
        // do nothing
    }

这只会在 $check = false 时重定向到消息页面;

This only redirects to the message page when $check = false;

最后一个有趣的事情是我只在一台服务器上遇到了这个问题,同样的脚本在 testserver 上运行完美.

Last funny thing is that I experience the problem only on 1 server, same script works flawlessly on testserver.

任何帮助将不胜感激!

推荐答案

你应该总是在完成 headers 之后运行 exit 以便浏览器的传输更快更稳定.

you should always run exit after you are finished with headers so that the transfer is faster and more stable for the browser.

试试这个方法:

if( ... )
{
     header("Location: message.php");
     exit;
}

// ...

请阅读评论以获取其他提示,了解为什么这是一个好主意.

Please read the comment for other tip's on why this is a good idea.

相关文章