HOWTO: Make a PHP Router

When I sat down to look at PHP, 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.

{% highlight ruby linenos %}

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

{% endhighlight %}

Direct Web Traffic Based on Request

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

{% highlight php linenos %}

{% endhighlight %}

Create the Necessary Views

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

{% highlight php linenos %} // views/home.php

Homepage

{% endhighlight %}

{% highlight php linenos %} // views/contact.php

Contact Us

{% endhighlight %}

{% highlight php linenos %} // views/404.php

Error 404

{% endhighlight %}

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.

{% highlight php linenos %}

php -S 0.0.0.0:3000 index.php

{% endhighlight %}

This is assuming of course that you have PHP installed.

If you found this tutorial helpful, please share it!

About the author

Hey, I'm Erik, a software engineer, gamer, writer, and content creator. I publish articles and tutorials about modern software development, design, and programming.

Get the newsletterBuy me a coffee

Wazoo