Is this a good way to handle 404 error?


I have the following on my site’s page.php file:

$page = $_GET['page'];
if (valid_page($page)) {
	echo $page['page_title'];
	echo $page['page_content'];
} else {
	header('HTTP/1.1 404 Not Found');
	header('Location: /404.php');

valid_page function checks whether the requested page exists or not in the database. Is this a good way to handle 404 errors? Do you have a better suggestion?

The most simple way would be to create handlers in your .htaccess file that point the error documents to custom HTML files explaining the error and why they got it, apart from that i can’t think of any simpler ways.

Hi Chris,

I know some of the .htaccess part and I have “ErrorDocument 404 /404.php” in my .htaccess file as well. But, that alone seems not to be enough without using my PHP code. If I don’t have my PHP code (which checks the existence of the page), when you type in a non-existent page, it doesn’t send to 404 page, it does nothing.

Instead of redirecting to the 404 file itself you can simply include that file directly into the page and exit the script straight after.