PHP,MVC,404 - 如何重定向到404?

Str*_*rry 3 php http-status-code-404

我正在尝试建立自己的MVC作为练习和学习经验.到目前为止,这就是我所拥有的(index.php):

<?php
require "config.php";

$page = $_GET['page'];
if( isset( $page ) ) { 
    if( file_exists( MVCROOT . "/$page.php" ) ) {
        include "$page.php";
    } else {
        header("HTTP/1.0 404 Not Found");
    }
}


?>
Run Code Online (Sandbox Code Playgroud)

我的问题是,我不能使用标头发送到404,因为标头已经发送.我应该重定向到一个404.html或有更好的方法吗?随意批评我到目前为止(它很少).我会喜欢建议和想法.谢谢!

Aus*_*yde 6

MVC框架中的标准做法是使用输出缓冲(ob_start(),ob_get_contents()ob_end_clean())来控制发送给用户的方式,时间和内容.

这样,只要您捕获框架的输出,就不会在您需要之前将其发送给用户.

要加载404,您将使用(例如):

<?php
require "config.php";

$page = $_GET['page'];
ob_start();

if (isset($page)) {
    echo "isset is true";
    if (file_exists(MVCROOT."/$page.php")) {
        include MVCROOT."/$page.php";
        $output = ob_get_contents();
        ob_end_clean();
        echo $output;
    } else {
        ob_end_clean(); //we don't care what was there
        header("HTTP/1.0 404 Not Found");
        include MVCROOT."/error_404.php"; // or echo a message, etc, etc
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.