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:
mysite.com/product.php?id=boroplus-12312
But I want to change the URL structure to that of Amazon and Flipkart. They use product names in the URL such as:
flipkart.com/boroplus-antiseptic-moisturising/someOtheProductParameters
amazon.com/boroplus-antiseptic-moisturising/someOtheProductParameters
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.
CodePudding user response:
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']);
array_shift($parts);
$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