Probably many of you learned to make rewrite mode like:
View Code HTML
RewriteRule (.*)/$ index.php?page=about |
Well, now i’ll learn you how to make a rewrite mode in the easy and prettier way.
Download .htaccess
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?get=$1 [QSA,NC,L]
|
So the above code should be the final .htaccess file.
You can use this file on any other project but you have to change only the RewriteBase
Okay now that we have the .htacces file, let’s create the php script.
View Code PHP
<?php $get = explode('/', $_SERVER['REQUEST_URI']); ?> |
This will create an array with parts of the url
so if we have example.com/page/about this script will return someting like:
Array(
[0]=>''
[1]=>'page'
[2]=>'about'
)
As you can see first value from the array is empty so we have to remove it with array_shift() function.
View Code PHP
<?php array_shift($get); ?> |
Now the array is
Array( [0]=>'page' [1]=>'about' )
Now let’s make the conditions
View Code PHP
<?php if($get[0] == 'page'){ if($get[1] == 'about'){ echo'The about page content.'; }else{ echo'Page not found.'; } }elseif($get[0] == 'article'){ if($get[1] == '1234'){ echo'The article content.'; }else{ echo'Article not found.'; } }else{ echo'Section not found.'; } ?> |
The final PHP:
Download rewrite.php
<?php $get = explode('/', $_SERVER['REQUEST_URI']); array_shift($get); if($get[0] == 'page'){ if($get[1] == 'about'){ echo'The about page content.'; }else{ echo'Page not found.'; } }elseif($get[0] == 'article'){ if($get[1] == '1234'){ echo'The article content.'; }else{ echo'Article not found.'; } }else{ echo'Section not found.'; } ?> |
2 Comments
very nice, easy and clean. Good job !
Wow! Pretty sweet. Thanks for sharing this