PHP,MVC,404-如何重定向到404? [英] PHP, MVC, 404 - How can I redirect to 404?

查看:147
本文介绍了PHP,MVC,404-如何重定向到404?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build my own MVC as a practice and learning experience. So far, this is what I have (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");
    }
}


?>

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

My problem here is, I can't use header to send to a 404 because the headers have been sent already. Should I just redirect to a 404.html or is there a better way? Feel free to critique what I have so far (it's very little). I would love suggestions and ideas. Thanks!

推荐答案

MVC框架中的标准做法是使用

Standard practice in MVC frameworks is to use output buffering (ob_start(), ob_get_contents(), and ob_end_clean()) to control how, when, and what gets sent to the user.

这样,只要您捕获框架的输出,就不会将其发送给用户,直到您想要它为止.

This way, as long as you capture your framework's output, it doesn't get sent to the user until you want it to.

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

To load the 404, you would use (for example):

<?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
    }
}
?>

希望有帮助.

这篇关于PHP,MVC,404-如何重定向到404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆