Strawberry
Strawberry

Reputation: 67968

Question related to 404 and PHP

So I'm using a single entry point found in a previous question of mine: How to include config.php efficiently?

We all know what 404 errors is, so no explanation needed there. However, when using the single entry point index.php?page=pokemon, it doesn't go to the 404 page when trying to access a page that is non-existent. So how can I solve this problem which would make it more user friendly and direct the visitors to my 404 page so they won't see all the PHP errors?

Upvotes: 1

Views: 263

Answers (3)

Gumbo
Gumbo

Reputation: 655745

If you’re actually using user187291’s code, alter it like this:

$page = "home";
if (isset($_GET['page'])) {
    $page = $_GET['page'];
}
$file = "$page.php";
if (preg_match('/\W/', $file) || !is_file($file)) {
    header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
    // print error message
    exit;
} else {
    include $file;
}

But since you’re using header, you need to make sure that no output has been sent to the client. Otherwise the HTTP header is already sent and you cannot modify it. You can use the output control functions to buffer any output and discard it in case of an error.

Upvotes: 0

KB22
KB22

Reputation: 6979

I assume you do sort of an if / elseif or a switch on the variable $page to figure out which page to display, right?

If so, just add an ELSE resp. default: branch which will display a custom error note to the user if an unexpected value is passed as $page.

HTH

Upvotes: 1

Ciarán Walsh
Ciarán Walsh

Reputation: 1866

You should output your own error page (you could just include() a .html file, for example), and set the HTTP status code using the header() function:

header("HTTP/1.0 404 Not Found");

Of course, you must set the header before including the error template.

Upvotes: 2

Related Questions