收录日期:2019/04/26 16:21:01 时间:2012-12-23 22:22:51 标签:php,http-status-code-404

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!

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.

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.

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