TheRogerLAB Codes

Create a friendly URLs router in PHP

  July, 2021

Introduction

We could build a php router using only query strings but in these days friendly URLs are preferred for SEO. So how can we convert our routes like folder/search.php?category=shoes into folder/category/shoes in php language. For static URLs here is an option:

Step 1: Create an .htaccess file in your root folder

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

In a few words this code means that all urls requested on our site will be redirected to the index.php file unless they physically exist.

Step 2: Create an index.php file in your root folder

<?php
//define the base_url ("myProject" is the project folder)
define("base_url""/myProject/");

//create the myRoutes function that is a whitelist for allowed urls
function myRoutes($uri){

  switch ($uri) {

    //main page
    case base_url:
      include 'pages/main.php';
      break;

    //category/shoes (friendly url)
    case base_url.'category/shoes':
      include 'pages/category/shoes.php';
      break;

    //category/shirts (friendly url)
    case base_url.'category/shirts':
      include 'pages/category/shirts.php';
      break;

    //Anyone else is not allowed
    default:
      echo '404 page not found';
      break;

  }
}

//calling the function and passing requested uri as param
$uri = $_SERVER['REQUEST_URI'];
myRoutes($uri);

?> 

For a functional example of this code download the demo and place it into your localhost (www or htdocs folder)

DOWNLOAD RATE THIS ARTICLE
4.6
18
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com