• Calculating...
  • 5 years ago
  • 8.6K Views
  • Archived This is an Archived post.
    The content within this may not be used or replaced with newer versions.

Simple PHP Page Router

This is a simple yet basic PHP routing application created to direct all request to index.php and route the files to it’s relevant paths.

 

  1. Create the Configuration file

In the root directory, Specify the configuration by creating a .htaccess file to redirect all requests to index.php.

 

.htaccess

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

  1. Create the Router

Specify the pages you want to redirect by adding the url in the switch statement. It will redirect to your specified file and if the url is not available then it’ll redirect to the default case.

index.php

<?php
$redirect = $_SERVER['REQUEST_URI']; // You can also use $_SERVER['REDIRECT_URL'];

switch ($redirect) {
    case '/'  :
    case ''   :
        require __DIR__ . '/pages/home.php';
        break;

    case '/contact' :
        require __DIR__ . '/pages/contact.php';
        break;
    default:
        require __DIR__ . '/pages/404.php';
        break;
}
 
  1. Create the Pages

Create the following home.phpcontact.php404.php files under pages directory and copy the below codes to each files.

pages/home.php

<h1>Home</h1>
 

pages/contact.php

<h1>Contact</h1>

pages/404.php

 
<h1>Error! Page Not Found.</h1>
 

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Share:

Related Post

Installing PHP on Windows

PHP is known to be one of the most commonly used server-side programming language on the web. It provides an easy to master with a simple learning curve. It has close ties with the MySQL database.

  • 3 years ago

Convert PHP Array To JSON : Examples

This tutorial focuses on converting PHP Array to JSON. It is used to read data from the server and display it to the Web. JSON is a text format , and We can convert any JS Object into a JSON format.

  • 5 years ago

Simple PHP MySQL CRUD Application

PHP is widely used by many developers today and it’s one of the easiest language to learn. This tutorial will help you to learn the basic CRUD (Create, Read, Update, Delete) operations.

  • 5 years ago

PHP Program to remove empty or specific array elements

This tutorial is created to remove specific or empty (NULL) array elements from the array.

  • 5 years ago

PHP Array Functions and their usage with examples

This tutorial is created to give an abstract idea about commonly used PHP array function with examples. Through this tutorial you’ll be able to know, how to use array functions to make code more short

  • 4 years ago