HOWTO: Make a PHP Router

Share: Twitter Facebook LinkedIn

It’s been a long time since I’ve tackled some PHP, so when I sat down to look at it again, 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.

1
2
3
4
5
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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.

1
2
3
// views/home.php

<h1>Homepage</h1>
1
2
3
// views/contact.php

<h1>Contact Us</h1>
1
2
3
// 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.

1
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!

Comments

You are seeing this because your Disqus shortname is not properly set. To configure Disqus, you should edit your _config.yml to include either a disqus.shortname variable.

If you do not wish to use Disqus, override the comments.html partial for this theme.