Simple PHP Page Router

This is a simple, Basic PHP routing application created to direct all request to index.php and route to the files.

  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]
  2. 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;
    }
  3. Create the Pages

    Create the following home.php, contact.php, 404.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.