The web server handles routing for PHP in its most used configuration. The request path is mapped to a file to do this: The web server will really search for a file with the name test.php in a predefined directory if you type in www.example.org/test.php.
For our needs, the following functionality is useful: You can also call www.example.org/test.php/hello on many web servers, and test.php will still be executed. PHP uses the $_SERVER['PATH INFO'] variable to make the extra files in the requested path available. In this instance, it would have "/hello" in it.
You can build a very simple router like this:
<?php
// First, let's define our list of routes.
// We could put this in a different file and include it in order to separate
// logic and configuration.
$routes = array(
'/' => 'Welcome! This is the main page.',
'/hello' => 'Hello, World!',
'/users' => 'Users!'
);
// This is our router.
function router($routes)
{
// Iterate through a given list of routes.
foreach ($routes as $path => $content) {
if ($path == $_SERVER['PATH_INFO']) {
// If the path matches, display its contents and stop the router.
echo $content;
return;
}
}
// This can only be reached if none of the routes matched the path.
echo 'Sorry! Page not found';
}
// Execute the router with our list of routes.
router($routes);
?>
I hope this helps you.