PHP .htacces and index.php redirection
Question by Emann Tumala Saligue
I am new about this redirection and I want to know how it works?
I have some file called index.php and i want to hadlle it any directory in the site
index.php
<?php
if(empty($dir)){
include('includes/home.php');
}
if($dir=='profile'){
include('includes/profile.php');
}
elseif($dir=='settings'){
include('includes/settings.php');
}
else{
include('includes/404.php');
}
?>
The url is:
test 1. www.example.com/ - will view the include home.
test 2. www.example.com/settings - will view the include settings.
test 3. www.example.com/errorsample - will view the include 404 page.
How to make .htaccess
and index.php using that code or any idea how it works and sample code of it.
Answer by Starx
I will try to explain this with a simple example. Consider the following .htaccess
file
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ /index.php?x=$1 [L]
# ^ This is the rule that does the redirection
What it does is, it routes every url request and sends the request to index.php. How it send it? I will show couple of example to do that.
www.example.com/settings
will be send aswww.example.com/index.php?x=settings
www.example.com/errorsample
will be send aswww.example.com/index.php?x=errorsample
So, now you are configure your index.php and decided what you want to do, with the value you get in $_GET['x']
switch($_GET['x']) {
case "profile": include("include/profile.php"); break;
// .... similarly other cases
default: include("includes/home.php"); break;
}
}