How to use Name in Ecommerce Product URL instead of parametrized ID

I am building a small ecommerce website using PHP. Right now, I am displaying data in product.php file using ?id=product_name parameter. So, the current URL structure looks like:

But I want to change the URL structure to that of Amazon and Flipkart. They use product names in the URL such as:

What I would have to change. Do I have to create folders on server or is there another way to do it? And how will I retrive the data from the database? Thanks.

>Solution :

First of all you need to create .htaccess file that makes all requests go to index.php, Like:

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/.*
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

Inside index.php you may read request url parts like:

$parts = explode('/', $_SERVER['REQUEST_URI']);
$product_name = $parts[0];

It’s not best practice to build your own request handler / router, Instead you may use a modern PHP Framework like Laravel, Symfony, or any MVC Framework

Leave a Reply