如果已经发送标题,我怎么能404页面?

use*_*327 2 php mysql http-headers http-status-code-404

我使用php GET检查URL中的ID,然后从匹配该ID的数据库中检索tekst.这是执行该操作的代码片段:

function getLyric() {
$id = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM lyrics WHERE id = ".$id."") or die(mysql_error());
if ($row = mysql_fetch_assoc($query)) { ?>
    <h1><?= $row['title']; ?> lyrics</h1>
    <h2><?= $row['author']; ?></h2>

    <pre><?= $row['lyrics']; ?></pre>
    <?php }
else { header("HTTP/1.1 404 Not Found"); header("Status 404 Not Found"); }
}
Run Code Online (Sandbox Code Playgroud)

这就是页面在我调用此函数的位置:

<?php include 'includes/header.php' ?>
<?php getLyric(); ?>
<?php include 'includes/footer.php' ?>
Run Code Online (Sandbox Code Playgroud)

不幸的是,函数中的404部分不起作用.我收到以下警告.Warning: Cannot modify header information - headers already sent by [redacted] functions.php on line 61.第61行是404部分; "else {header}〜".

我从Stackoverflow了解到这是因为该<html><head>部分已经在页面上输出,所以我不能再改变它了.这是对的?

以前当我没有其他〜部分我只是得到一个空白页面.在这种情况下如何正确发送404?如果我不能最接近什么选项?

net*_*der 5

您只需要将逻辑与演示文稿分开:

function getLyric() {
    $id = (int)$_GET['id'];
    $query = mysql_query("SELECT * FROM lyrics WHERE id = ".$id."") 
                 or die(mysql_error());
    return mysql_fetch_assoc($query);
}
Run Code Online (Sandbox Code Playgroud)

...然后:

<?php
$row = getLyric();

if (!$row) {
    header("HTTP/1.1 404 Not Found");
    exit;
}

include 'includes/header.php' 
?>

<h1><?= $row['title']; ?> lyrics</h1>
<h2><?= $row['author']; ?></h2>

<pre><?= $row['lyrics']; ?></pre>

<?php 
include 'includes/footer.php'
?>
Run Code Online (Sandbox Code Playgroud)