避免重定向循环。

3

我刚刚完成了网页维护功能的安装。以下是index.php代码:

    <?php
        session_start();
        require_once("system/functions.php");
        require_once("system/config.php");
        if($maintenance == 1){
            require_once(header("Location: index.php?page=maintenance"));
            die();
            session_destroy();
        }elseif($maintenance == 0)
        {
            getPage();
        }
    ?>

我也尝试过使用

    header("Location: index.php?page=maintenance");

不要使用上面的require_once头文件代码,而是使用以下代码。但是,如果我放置了

    require_once("frontend/pages/maintenance.php");

它会起作用。问题在于人们可以在地址栏中输入他们想要的任何页面,这些页面将显示出来。我需要它使用自己的URL(使用上述2个头代码有效,但我会得到太多的重定向错误),无论如何,您都将被重定向到此URL以查看维护屏幕。

维护.php文件的php部分:

<?php
if($maintenance == 0){
    header("Location: index.php?page=index");
    die();
}
else{
    header("Location: index.php?page=maintenance");
    die();
}
?>

我可以在maintenance.php文件中删除else代码部分,但这样它将始终重定向到“网站名称”/index.php(尽管仍然是维护屏幕,与上述相同的问题)

所以当有维护时,我需要更改我的代码,无论如何都会重定向到index.php?page=maintenance。如果我漏掉了一些细节,很抱歉,现在已经很晚了。如果需要的话,请随时问我:)


实际上显示维护页面的代码在哪里?在index.php还是maintenance.php中? - trincot
它在maintenance.php文件中。现在问题已经被修复了 :) - Xsef
1个回答

3

看起来你正在进行循环。当你在index.php脚本中时,以下内容将被执行:

require_once(header("Location: index.php?page=maintenance"));

实际上,您加载的是已经运行的脚本。它将再次查找 maintenance==1 并再次执行完全相同的操作。

您应该只重定向一次,然后当您发现已经在 page=maintenance URL 上时,实际上会显示您想要显示的维护消息,如下所示:

session_start();
require_once("system/functions.php");
require_once("system/config.php");
if($maintenance == 1){
    if ($_GET['page']) == 'maintenance') {
        // we have the desired URL in the browser, so now
        // show appropriate maintenance page
        require_once("frontend/pages/maintenance.php");
    } else {
        // destroy session before exiting with die():
        session_destroy();
        header("Location: index.php?page=maintenance");
    }
    die();
}
// no need to test $maintenance is 0 here, the other case already exited
getPage();

请确保在 frontend/pages/maintenance.php 中不要重定向到 index.php?page=maintenance,否则可能会陷入循环。

因此,frontend/pages/maintenance.php 应该像这样:

// make sure you have not output anything yet with echo/print
// before getting at this point:
if($maintenance == 0){
    header("Location: index.php?page=index");
    die();
}
// "else" is not needed here: the maintenance==0 case already exited

// display the maintenance page here, but don't redirect.
echo "this is the maintenance page";
// ...

1
非常感谢!现在它完美地工作了,正是我想要的方式 :) - Xsef

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接