【问题标题】:PHP which is the best practise of header locationPHP 这是标头位置的最佳实践
【发布时间】:2014-07-22 11:49:24
【问题描述】:

我在使用 PHP header location 时感到困惑。哪种方式是最佳实践...?

if(true){
    header("location:somepage.php");
}

或

if(true){
    header("location:somepage.php");
    exit;
}  

【问题讨论】:

标签: php redirect http-headers


【解决方案1】:

第二个是正确的,因为页面会自动重定向到你在标题语法中指定的页面。所以不需要退出。

【讨论】:

    【解决方案2】:

    header() 和 exit() 语句是一个好习惯。如果你不写 exit() 它将在重定向导致问题后执行一些语句。 exit() 将停止所有进一步的执行。

    header("location:somepage.php");
    exit;
    

    【讨论】:

      【解决方案3】:

      我认为如果你不使用“退出”,你的脚本的其余部分将在重定向之前执行。

      【讨论】:

        【解决方案4】:

        这取决于你想做什么: 如果您希望脚本的其余部分在更改标头后仍然运行 - 使用第一个选项(不带 exit() )。 如果(更有可能)您不希望脚本继续 - 使用第二个选项(使用 exit() )

        【讨论】:

          【解决方案5】:

          我肯定会选择第二个选项。否则脚本执行不会终止。单独设置另一个标头不足以重定向。

          【讨论】:

            【解决方案6】:

            在发送初始标头后,标头将继续发送 - 因此,如果您真的是认真的 - 您可以用 exit; 结束脚本。

            但问题是,您可能仍希望在用户被重定向到另一个页面后执行脚本 - 所以您实际上并不想输入 exit;。

            好代码示例:

            header("location:somepage.php");
            //continue code and do stuff.
            

            错误代码示例:

            header("location:somepage.php");
            // Continue code and do other stuff... then...
            header("location:somepageOtherPage.php");
            // This is the header that the user will get.
            

            【讨论】:

              【解决方案7】:

              发送 `Location:' 标头后 PHP 将继续解析,并且 header() 调用下面的所有代码仍将被执行。因此,请改用您的第二个示例:

              if(true){
                     header("location:somepage.php");
                     exit;
                }
              

              【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2010-09-30
              • 2014-02-15
              • 1970-01-01
              • 2011-12-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多