404 Page in a File-Based PHP Engine
If a user enters an incorrect URL into the address bar, we must show an error page. Let the content of the error page be stored in a corresponding file:
<div>
page not found
</div>
To determine the incorrectness of a request, we need to check the existence of the content file corresponding to the requested URL:
<?php
$path = 'view' . $url . '.php';
if (file_exists($path)) {
// file exists
} else {
// file does not exist
}
?>
Let's serve the content file if it exists, and the error file if there is no content:
<?php
$path = 'view' . $url . '.php';
if (file_exists($path)) {
$content = file_get_contents($path);
} else {
$content = file_get_contents('view/404.php');
}
?>
In case of an error, we must send a
header with a 404 error to the browser to
explicitly indicate that the page was not found.
Let's do that:
<?php
$path = 'view' . $url . '.php';
if (file_exists($path)) {
$content = file_get_contents($path);
} else {
header('HTTP/1.0 404 Not Found');
$content = file_get_contents('view/404.php');
}
?>
Implement the delivery of a page
with a 404 error in your engine.