The Simplest PHP Router
Blog Author
Theresa Underwood
  • Sep 10, 2021
  • 9 min to read

We wanted to create the absolute most basic routing code in PHP, so here it is. We will direct ALL traffic to index and route to the new files from here.

Redirect all requests to index.php

In the root of your project, create a .htaccess file that will redirect all requests to index.php.

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

Create a routing switch

Get the requested path with $_SERVER['REQUEST_URI'], and require the page you want to display. I have '' and '/' for both url.com/ and url.com.

index.php
<?php

$request = $_SERVER['REQUEST_URI'];

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

Create the views

Create a /views directory and place the files.

/home.php
<h1>Main</h1>
/views/about.php
<h1>About</h1>
/error.php
<h1>404</h1>

That's it!

Files on Github

Comments:

Blog Comment
Sophie Asveld

February 14, 2021

Email is a crucial channel in any marketing mix, and never has this been truer than for today’s entrepreneur. Curious what to say.

Blog Comment
Ariana Gerad

February 14, 2021

Email is a crucial channel in any marketing mix, and never has this been truer than for today’s entrepreneur. Curious what to say.

Blog Comment
Sophie Asveld

February 14, 2021

Email is a crucial channel in any marketing mix, and never has this been truer than for today’s entrepreneur. Curious what to say.

Leave a comment:

Contact Information

Sinhcoms
Nalanda Bihar, India

We're Available 24/7. Whatsapp Now. (+91) 9123288803 (121)255-53333
Find us here