Search⌘ K

Routing: Displaying the Not Found Error

Understand how to display custom 404 Not Found errors in your PHP project by managing routing and URL mappings. Learn to separate homepage logic, create user-friendly error pages, and organize scripts outside the public directory for improved project structure.

Creating a new homepage script

When the user provides a bad URL, we should show them a “Page not found” error instead. The homepage shouldn’t be the default page, it should only show up if we actually go to http://APPLINK/.

First, let’s move the code for the homepage to its own file: public/homepage.php.

PHP
<?php
include(__DIR__ . '/../bootstrap.php');
$title = 'Homepage';
include(__DIR__ . '/../_header.php');
?>
<h1>This is the homepage</h1>
<p><a href="/random.php">Get yourself a random number</a></p>
<?php
include(__DIR__ . '/../_footer.php');

We should then update the $urlMap to also include the URL /, which loads the new homepage.php script:

PHP
<?php
$urlMap = [
'/login' => 'login.php',
'/logout' => 'logout.php',
'/name' => 'name.php',
'/pictures' => 'pictures.php',
'/random' => 'random.php',
'/secret' => 'secret.php',
'/' => 'homepage.php'
];

Verify that this works by going to http://APPLINK/. We should see the homepage, but instead, we get a rather bad error:

Note: Remember, we have used http://APPLINK just as a substitute for localhost. The URL link on which the application will be available after running the code is located below the ...