PHP, MVC, 404 - How can I redirect to 404?

十年热恋 提交于 2020-06-26 04:36:27

问题


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");
    }
}


?>

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!


回答1:


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.

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

Hope that helps.




回答2:


Im not very good at english but i will try; the 404 error trigers on the server before running any code (because is suposse that the page does not exist, so there is no code).

So, if you want to give the user a 404 error seeking for the error in a php code, you must use a simple redirection to a 404.html.

In other hand, if you have access to the server config files you can program this on the server instead of a web page running on it. You can use WAMP to practice...

I hope you understand me. Cyaa

EDIT i must add:

$page = $_GET['page'];

This will give you an error if $_GET['page'] is not set, you MUST check for isset($_GET['page']) before trying using it.




回答3:


You should either redirect or simply include it, here is modified code:

require "config.php";

$page = $_GET['page'];
if( isset( $page ) ) { 
    echo "isset is true";
    if( file_exists( MVCROOT . "/$page.php" ) ) {
        include  MVCROOT . "$page.php";
    } else {
        include  MVCROOT . "404.html";
    }
}


来源:https://stackoverflow.com/questions/3050425/php-mvc-404-how-can-i-redirect-to-404

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!