繁体   English   中英

标头位置无法重定向

[英]header location unable to redirect

概述:

我在检查条件的代码块中,如果条件( mysqli_num_rows($pages_set)>0 )满足,则重定向到页面( manage_contents.php ),因此if条件之后的所有内容都不应作为标题执行已被重定向。

if(mysqli_num_rows($pages_set)>0) {
    $_SESSION["message"] = "can't delete a subject with pages";
    redirect_to("manage_contents.php?subject={$current_subject["id"]}");    
}

    $id = $current_subject["id"];

    //Standard delete query
    $query = "DELETE FROM subjects WHERE id = {$id} LIMIT 1";
    $result = mysqli_query($connection,$query);

    if($result && mysqli_affected_rows($connection)==1) {
        $_SESSION["message"] = "Subjects deleted";
        redirect_to("manage_contents.php");
    }else{
        $_SESSION["message"]="Subject deletion failed";
        redirect_to("manage_contents.php?subject={$id}");   
    }

但是,如果我执行上面的代码,则代码不会重定向(即使满足if条件)也不执行if循环旁边的任何内容。

redirect_to函数:

function redirect_to($new_location) {
        header("Location:".$new_location);  
    }

对我来说可行的解决方案:

if(mysqli_num_rows($pages_set)>0) {
        $_SESSION["message"] = "can't delete a subject with pages";
        redirect_to("manage_contents.php?subject={$current_subject["id"]}");    
    } else {

        $id = $current_subject["id"];

        //Standard delete query
        $query = "DELETE FROM subjects WHERE id = {$id} LIMIT 1";
        $result = mysqli_query($connection,$query);

        if($result && mysqli_affected_rows($connection)==1) {
            $_SESSION["message"] = "Subjects deleted";
            redirect_to("manage_contents.php");
        }else{
            $_SESSION["message"]="Subject deletion failed";
            redirect_to("manage_contents.php?subject={$id}");   
        }
}

因此,如果我将所有代码放入else语句中,那么当if条件满足时,它就不会进入else部分,因此可以正常工作。

怀疑:

如果仅将代码保留在else节之外,为什么标头不重定向,为什么当代码位于else块内部时标头重定向就很好?

我认为这两个代码应该完全按照我对标头重定向的了解完全相同(当标头被重定向时,以下所有代码执行都应跳过)。

设置Location标头不会停止当前PHP页面的处理。 您需要显式exit

function redirect_to($new_location)
{
    header("Location: $new_location");
    exit;
}

在其他语言/框架(想到ASP.NET的Response.Redirect )中,当前页面的执行将为您停止,但这在PHP中不会发生,并且header的文档中没有任何指示。

看一下http://php.net/manual/en/function.header.php中的警告:当您使用“ Location”标头时,必须注意不要执行下面的代码(第二个代码将不被执行)。代码遵守)。

暂无
暂无

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

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