views:

69

answers:

4

So I'm using a single entry point found in a previous question of mine: http://stackoverflow.com/questions/1712973/how-to-include-config-php-efficiently/1713000#1713000

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?

+2  A: 

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.

Ciarán Walsh
You do mean `header("HTTP/1.0 404 Not Found", true, 404);` don't you.
nikc
No I didn’t, why?
Ciarán Walsh
Both will work (see http://www.php.net/manual/en/function.header.php). However, nikc's example is more verbose.
Salman A
+1  A: 

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

KB22
A: 

If you’re actually using stereofrog’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.

Gumbo
A: 

You must send a 404 status code to the browsers and search engine robots, using the header function.

<?php
  // if page does not exist then
  header("HTTP/1.0 404 Not Found");
  // followed by html content indicating what went wrong
?>

I am not sure whether redirecting to an error page is a good idea or not. I'd rather avoid it so that search engines do not get confused.

Salman A