当 header(Location: xxx) 在里面时 PHP if 语句被忽略 [英] PHP if-statement ignored when header(Location: xxx) is inside

查看:17
本文介绍了当 header(Location: xxx) 在里面时 PHP if 语句被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题.我的页面顶部有一个 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.

这篇关于当 header(Location: xxx) 在里面时 PHP if 语句被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆