加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 21:37:31 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试建立自己的MVC作为练习和学习经验.到目前为止,这就是我所拥有的(index.php): ?phprequire "config.php";$page = $_GET['page'];if( isset( $page ) ) { if( file_exists( MVCROOT . "/$page.php" ) ) { include "$page.php"; } else { header("HT
我正在尝试建立自己的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");
    }
}


?>

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

解决方法

MVC框架中的标准做法是使用 output buffering(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
    }
}
?>

希望有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读