Make pretty URLs with PHP URL Routing
For the past couple of days, I wonder on how to make my URLs pretty for SEO purposes and make a clean approach to my web applications. We are currently studying MVC for ASP.Net in our computer elective IV and one of the topic is about URL Routing. Since I’m a PHP developer, I made some research on how to implement URL Routing with PHP. It is very easy to implement and to understand. Here is a quick example.
Required Files:
.htaccess
index.php
.htaccess:
Options +FollowSymLinks
IndexIgnore */*
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
For example: http://www.example.com/post/12
To get the values from your url in your index.php file:
$uri = explode('/', $_SERVER['REQUEST_URI']);
echo $uri[1]." ".$uri[2]; //Outputs post 12
Furthermore using switch:
$uri = explode('/', $_SERVER['REQUEST_URI']);
switch($uri[1]){
case "post":{
$postId = $uri[2];
require_once("post.php");
break;
}
default:{
require_once("default.php");
break;
}
}
The above example will now direct you to a post with a postId of 12. This is a quick example of PHP URL routing for you. For further discussion visit my resource for this post.
