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.


$request = $_SERVER['REQUEST_URI'];

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


Create the Necessary Views

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

// views/home.php


// 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 index.php

This is assuming of course that you have PHP installed.

If you found this tutorial helpful, please share it!