Header 导致 404 错误的位置

Header Location resulting in a 404 error

我试过使用 header 函数。但是当我点击登录按钮时它会显示一条错误消息。 我的登录文档在:XAMPP\htdocs\Website\includes\login.inc.php 我的索引文档在:XAMPP\htdocs\Website\index.php

希望有人能提供帮助。

<?php

session_start();

if (isset($_POST['submit'])) {

include 'dbh.inc.php';

$gebr = mysqli_real_escape_string($conn, $_POST['gebr']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

//Foutmeldingen
    //Check of de velden leeg zijn
    if (empty($gebr) || empty($pwd)) {
        header("Location: ../index.php?login=empty");
        exit();
    } else {
        $sql = "SELECT * FROM stemmer WHERE Naam='$gebr'";
        $result = mysqli_query($conn, $sql);
        $resultCheck = mysqli_num_rows($result);
        if ($resultCheck < 1) {
            header("Location: ../index.php?login=error");
            exit();
        } else {
            if ($row = mysqli_fetch_assoc($result)) {

                if ($row['Wachtwoord'] != $pwd) {
                    header("Location: ../index.php?login=error");
                    exit();
                } else{
                    //Log de gebruiker hier in
                    $_SESSION['u_id'] = $row['idStemmer'];
                    $_SESSION['u_naam'] = $row['Naam'];
                    $_SESSION['u_gemeente'] = $row['idGemeente'];
                    $_SESSION['u_partij'] = $row['idPartij'];

                    header("Location: ../index.php?login=succes");
                    exit();
                }
            }
        }
    }
} else {

    header("Location: ../index.php?login=error");
    exit();
}

包含文件时,URI 不变。因此,您仍会根据加载的 URI 引用链接或位置。

根据您的 404 错误,您可能将此文件包含在与 index.php 相同的 Web 目录中,因此不应将位置设置为 ../index.php?login=error返回一个目录,但 index.php?login=error 会尝试在同一 Web 目录中加载 index.php。

您还可以使用 /index.php?login=error/ 前缀),它会从 Web 根目录加载 index.php。如果你要在许多不同的文件中加载这个包含文件,最好使用像这样的根相对路径。

您可以使用输出缓冲来解决这个问题,在您发送之前,所有发送到浏览器的输出的开销都在服务器中缓冲。您可以通过在脚本中调用 ob_start() 和 ob_end_flush() 或在 php.ini 或服务器配置文件中设置 output_buffering 配置指令来完成此操作。

使用ob_start()

阅读本文Notes