Erik Yuzwa

HOWTO: Make a PHP Router

August 01, 2020 | 2 Minute Read

I wanted to start with a simple router. The idea being that all requests are forced to the index.php where the decision is made where to send the traffic.

If it’s been a while since you’ve looked at PHP, or are just starting out, then maybe this will help you out as well.

Force all requests to index.php

In the root of your project folder, create an .htaccess file. This is a “special” file that is used by most web servers.


RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]

Direct Web Traffic Based on Request

Get the requested path with $_SERVER["REQUEST_URI"], and require the page you want to display.


<?php

$request = $_SERVER['REQUEST_URI'];

switch ($request) {
    case '':
    case '/' :
        require __DIR__ . '/views/home.php';
        break;
    case '/contact' :
        require __DIR__ . '/views/contact.php';
        break;
    default:
        http_response_code(404);
        require __DIR__ . '/views/404.php';
        break;
}

?>

Create the Necessary Views

Create the /views folder, and create any view files you need.

// views/home.php

<h1>Homepage</h1>

// views/contact.php

<h1>Contact Us</h1>

// views/404.php

<h1>Error 404</h1>

Running the PHP Server from the command line

To test out any of your local PHP files, you can take advantage of the PHP command-line interface (cli) to start a running PHP-capable webserver.


php -S 0.0.0.0:3000 index.php

This is assuming of course that you have PHP installed.

If you found this tutorial helpful, please share it!