Tue 16 Jan 2007
Introduction
As you may know, clean URLs can be made with Apache’s mod_rewrite, but you are able to make clean URLs with PHP only.This tutorial requires minimum knowledge of PHP.
Contents
This tutorial is split up into the following parts:
Method one
Implementing method one
Method two
Implementing method two
Conclusion
Method one
The second method will take /users/2 and it’s purpose is to go to the users page on page 2.
$array = explode('/',$_SERVER['PATH_INFO']);
array_shift($array);
?>
PHP contains several predefined variables, one of them is $_SERVER[’PATH_INFO’]. To know what the first line does you must know the explode function. The explode function takes two arguments. The first is the seperator and the second is the string. The explode function takes the string and splits it up where the seperator is.
array_shift removes the first key of an array.
Implementing method one
First you should put the above snippet in a file called something like clean_urls.php and include it on the top of your pages (or if you only have one page, just put it in the top).
Here is how you could use it:
include 'clean_urls.php'; // Include the snippet
'home',
'users',
'login',
'register',
'admin',
);
$module = $array[0]; // The first key contains what we will use as our module
$page = $array[1]; // The second key contains what we will use as the page number
if(empty($module)) // We need a default module
{
$module = "home";
}
if(in_array($module,$modules)) // Does the requested module exist?
{
include "./modules/{$module}.php"; // If yes: Include it
}
else {
die("Failed to load module '{$module}'"); // If no: Error message
}
?>
Then you would use the page variable for something useful in your module page.
Method two
The second method will convert /func/users/page/2 into what ?func=users&page=2 would have done.
$array = explode('/',$_SERVER['PATH_INFO']);
{
$_GET[$array[$i]] = $array[$i+1];
}
?>
Here the first line is the exact same line as in method one.
Next we have a for loop. It starts by setting $i to 1, then it will run as longs as the second statement ($i<=count($array)-1) evaluates to true and by the end of each iteration it will add 2 to $i. Inside the loop we add to the $_GET variable.
Implementing method two
Method two is easy to implement. Just put the above snippet in a file called something like clean_urls.php and include it on each page.
Conclusion
As you see, clean URLs are very easy to make with PHP only. With only 2-4 lines, you can have clean URLs.
February 7th, 2011 at 4:44 pm
thanks,
great tut