Now you can provide your feedback to our articles!

How to create custom router in PHP

Last updated : Dec 11, 2021

How to create custom router in PHP



MVC frameworks provide you a way to keep your application's routes very clear, concise and SEO friendly but what if you are creating application in PHP because in core PHP you always get a page name with an extension '.php' in url bar. But knowing the fact that frameworks are written in PHP itself so we can create custom router in PHP just like any other framework.



Continue reading this article to know how to create a custom router in PHP.



Not only it custom routes make your PHP application an efficient one but also it makes your application very much SEO friendly.
PHP pages are treated like any other HTML, CSS or JS files which can be easily crawled and indexed in search engine results.

Let's get started.


Logic The logic or idea behind creating custom router in PHP is redirecting every url on one page and in PHP the default page is index.php and after redirection we need a file for handling routes and giving the way ahead.


Note : We have created a virtual host named http://php-route.test/ for this article and we will create and test our application on this domain. If you face any problem working on localhost, please sign in and comment your error and we'll help you in solving the error.


Step 1 : Creating and setting up a directory
We are creating a directory php_route_project and if you are working on localhost then you have to create a directory in htdocs directory.


Step 2 : Creating .htaccess file
In php_route_project directory create a new .htaccess and write the following code.

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


Step 3 : Creating routes handling file
In php_route_project directory create a new index.php and write the following code.

<?php
        $url_requested = $_SERVER['REQUEST_URI'];
        $url_len = strlen($url_requested);
        
        $actual_path = substr($url_requested,strpos($url_requested,'/'),$url_len); 
    
        if($actual_path == "/"){
            $page_title = "Php route project - Home";
            include_once('./home.php');
        }    
        else if(preg_match("!/products/[a-z,A-Z,0-9]!",$actual_path)){
            $actual_route = substr($actual_path,(strrpos($actual_path,'/')+1),$url_len);
            $actual_route = str_replace("%20"," ",$actual_route);  
            $data_arr = [
                'content_to_show' => $actual_route
            ];      
            $page_title = "Php route project - ".$actual_route;
            include_once('./products.php');
        }
        else if($actual_path == "/products"){        
            $page_title = "Php route project - Products";
            include_once('./products.php');
        }
        else if($actual_path == "/solutions"){
            $page_title = "Php route project - Solutions";
            include_once('./solutions.php');
        }    
        else {
            $page_title = "error 404 not found!";
            include_once('./404.php');
        }
    ?>


Script explanation First we are getting the current complete URL with PHP's index REQUEST_URI of global array $_SERVER.

Then we get the length of the that URL.

Then we get the after / part of the url so we extract that part from $url_requested by substring from the position of / from starting and till the end of the string's length.

Now we have the actual path in $actual_path variable and now we can decide what to do according to the route name

So first one is root one, in this we will simply include home.php file which we will create in a while.

And in the second if condition you will see a preg_match() function to check additional values appended in url. For eg. we have a url /product/product1 so in this case details of product1 should be visible on the page. Further in this article we will see how we do this.

And the rest of the if conditions we are simply checking $actual_path with certain strings and if they match we simply add page_title and include the respective files and render.


Step 4 : Before creating files for rendering, we will create a common navigation menu file
So create a file named navbar.php and write the following script.

<head>
        <title><?php echo $page_title; ?></title>
        <style>
            body{margin:0;}
            .navbar{
                list-style-type:none;
                padding:10px;
                margin:0;
                background-color:rgb(220,220,220);
            }
            .navbar > li{
                display:inline;
                margin:10px;
            }
            .div_for_content{
                margin:50px 0 0 0;
                padding:15px;
                text-align:center;
                background-color:rgb(200,200,200);
                font-size:20px;
            }
        </style>
    </head>
    
    
        <ul class="navbar">
            <li>
                <a href="/">
                    Home
                </a>
            </li>
            <li>
                <a href="/products">
                    Products
                </a>
            </li>
            <li>
                <a href="/solutions">
                    Solutions
                </a>
            </li>
        </ul>


Step 5 : Creating home page file for rendering
So create a file named home.php and write the following script.

<body>
        <?php include_once('./navbar.php'); ?>
        <p style="margin-top:50px;">This is home page.</p>
    </body>


Step 6 : Creating products page file for rendering
So create a file named products.php and write the following script.

<body>
        <?php include_once('./navbar.php'); ?>
    
        <?php
            if(isset($data_arr) && !empty($data_arr)){
        ?>
            <div class="div_for_content">
            You are viewing<br/><br/>
            <?php echo $data_arr['content_to_show']; ?>
            page
                </div>
        <?php
        }
        else {
        ?>
        <p style="margin-top:50px;">This is products page.</p>
        <ul>
            <li><a href="/products/product 1">Product 1</a></li>
            <li><a href="/products/product 2">Product 2</a></li>
            <li><a href="/products/product 3">Product 3</a></li>
            <li><a href="/products/product 4">Product 4</a></li>
            <li><a href="/products/product 5">Product 5</a></li>
        </ul>
        <?php
        }
        ?>
    </body>


Step 7 : Creating solutions page file for rendering
So create a file named solutions.php and write the following script.

<body>
        <?php include_once('./navbar.php'); ?>
        <p style="margin-top:50px;">This is solutions page.</p>
    </body>


Take a look of the video for output.


That it it for this article, you learnt to create your own router in PHP today. We will bring more articles like this providing you important information related to programming.



Setup react and express on sam...

Read more

How neurons in brain function

Read more

Run C++ as CGI script in web b...

Read more

Real time chat application usi...

Read more

How to setup lemp stack in ubu...

Read more

How to secure phpmyadmin in Ub...

Read more

How to create real time notifi...

Read more

How to create simple api in no...

Read more

Task scheduling with cron job ...

Read more

How to use modules in Javascri...

Read more

Create a multi language(lingua...

Read more

Create food ordering app - Foo...

Read more

Linear Regression in machine l...

Read more

Create simple web application ...

Read more

Why algorithms can drive the i...

Read more

Why Javascript frameworks are ...

Read more

Create authenticated API in La...

Read more

Create simple and static websi...

Read more

Setup Pusher app

Read more

Laravel Installation and setti...

Read more

Realtime chat application in L...

Read more

Working of neurons (the easy w...

Read more

Progressive web app

Read more

Sign in for comment. Sign in