The Simplest PHP Router

The Simplest PHP Router

Tania Rascia  /  3 responses

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

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['REDIRECT_URL'], and require the page you want to display. I have '' and '/' for both url.com/ and url.com.

index.php

<?php

$request = $_SERVER['REDIRECT_URL'];

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

Create the views

Create a /views directory and place the files.

/views/index.php
<h1>Main</h1>
/views/about.php
<h1>About</h1>
/views/404.php
<h1>404</h1>

That’s it!

Quality and morality on the web

Hi, my name is Tania Rascia. I've turned down every advertiser, sponsored post, and affiliate who has come to me. I give away all my knowledge for free to 300,000+ monthly readers and helped thousands of people learn and successfully transition into a design/development career.

You know what I stand for, and you know my commitment to you - no bullshit, no sponsored posts, no pop ups, no blocked content, ads, schemes, tactics, or gimmicks. Just free, quality content. If you enjoy my content, please consider supporting what I do!

Write a response

Your email address will not be published.

All code will be displayed literally.

Discussion