How to create your own custom router in PHP

Category
Tutorial
Reading
3 mins
Views
1.9K
Posting
03 Mar 2024

Routing is a method commonly used in frameworks to manage HTTP requests on websites. In the context of PHP, this method is often implemented in frameworks such as Symfony, Laravel, or Codeigniter. Routing can also be said to be a process of mapping or controlling according to the user's direction. This method greatly facilitates and speeds up the development process because there is no need to set it up one by one, which means the system will automatically direct according to what we have determined. For example, in Laravel, you can see the code example below:

Route::get('/contact', 'ContactController@index');

The HTTP GET request received from the URL "/contact", Laravel will call the index method of the contact controller, which handles the process. In this article, I will provide a simple tutorial on how to create custom routing without using any framework or native PHP.

 

How to create your own custom router in PHP

 

 

1. Creating a Routes.php file

The first step is to create a Routes.php file that contains a list of web pages that can only be accessed by users. In this example, I only display 3 pages: home, contact, and blog.

<?php

// Routes.php
// How to create your own custom router in PHP - genelify.com

return [
    '/' => __DIR__ . DIRECTORY_SEPARATOR . 'pages/home.php', 
    '/contact' => __DIR__ . DIRECTORY_SEPARATOR . 'pages/contact.php', 
    '/blog' => __DIR__ . DIRECTORY_SEPARATOR . 'pages/blog.php', 
];

Please adjust the path of the home, contact, and blog files according to the folder structure of your project. I suggest separating the logic code and setting the route itself. The goal is that by creating this Routes.php file, we will need to be confused if we want to add a new page because it is made separately.

 

2. Creating the logic code for the PHP Routing method

After we finish creating the Routes.php file, we will create the logic of the HTTP request received by the server according to the routes that we have determined. In your index.php file, add this code:

<?php

// index.php
// How to create your own custom router in PHP - genelify.com

// Current location
$request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; 

// Avoid error on homepage URI
$request_uri = strlen($request_uri) === 1 && $request_uri === '/' 
? $request_uri : rtrim($request_uri, '/');

// Get all routes
$routes = include __DIR__ . DIRECTORY_SEPARATOR . 'Routes.php';

// Show current page on browser
if(array_key_exists($request_uri, $routes)) 
{
    // Load file
    include $routes[$request_uri];
    exit();
}

// Show not found page to browser
http_response_code(404);
exit('Page Not found');

 

3. PHP routing logic explanation

Now that we know the logic of handling HTTP requests with routing, I'll go through it line by line to understand how this code works on your server.

$request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';

This line of code aims to get the URI (Uniform Resource Identifier) of the current request in the browser. This is taken from the super global variable $_SERVER['REQUEST_URI']. If "REQUEST_URI" is not set or empty, then the default value is an empty string.

$request_uri = strlen($request_uri) === 1 && $request_uri === '/' 
? $request_uri : rtrim($request_uri, '/');

This is a way to avoid errors caused by trailing slashes "/" in URIs, often occurring in main or home pages that have no path. If the length of the $request_uri string is one, then the string obtained does not need to be changed. If more than one is found, the trailing slash string is removed using PHP's rtrim() function.

$routes = include __DIR__ . DIRECTORY_SEPARATOR . 'Routes.php';

This is a way to get a list of all the routes that exist in your application that we created earlier. These routes are stored in the Routes.php file, and the $routes variable contains an array that maps the URI to the file location corresponding to the user's request in the browser.

if(array_key_exists($request_uri, $routes)) 
{
    include $routes[$request_uri];
    exit();
}

In this line, the system checks whether the requested URI is in the route list defined by you. If it does, then the file corresponding to that URI will be called and loaded for display in the browser. This means that if the URI matches one of the routes defined in Routes.php, the application will load the page that you defined. In this example, I did not use a switch statement because, in my opinion, using array_key_exists() is much simpler and easier to understand. If you want to use a switch statement, you can change it as you wish.

http_response_code(404);
exit('Page Not found');

In the last line of code, if the HTTP request does not have a matching URI in the route list that you have defined in Routes.php, then the system will set the HTTP code 404 (Not Found) status using the http_response_code() function to the browser, then display the message "Page Not Found" to the browser. This indicates that the requested page was not found because it is not listed in Routes.php.

And to enable this routing method, don't forget to add the code below in your .htaccess file.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]

 

Conclusion

Routing is the process of determining how HTTP requests are handled in a web application. It also prevents unauthorized access to certain parts of your application and ensures that each HTTP request is forwarded to the appropriate page.

Using routing in web applications allows you to build structured, secure, and maintainable applications and separates the different processes in web application development.

Share