Routing: Mapping URLs
Learn how to create a simple PHP router.
Purpose of routing
Another important concept that needs to be discussed before we move on to the next chapter is routing. We will be discussing it because of the following two concerns:
- We have
.php
in every page URL, which does not look great. A URL that looks like/pictures
instead of/pictures.php
needs to be used. - The URL of a page is tied to its file name, which does not give us flexibility. A URL that looks like
/random-number
, which shows the output of therandom.php
script, needs to be used. We also want to be able to rename that file, while the URL stays the same and vice versa ( we should be able to change the URL without changing the name of the script).
Once all of this is possible, we can move the page scripts out of public/
because they no longer need to be publicly accessible.
Instead, we will have one entry point for the PHP server, the index.php
file, which will inspect the URL of a request and include the right PHP script.
Get hands-on with 1400+ tech skills courses.