The basics of php routing
Solution 1
In its most common configuration, PHP relies on the web server to do the routing. This is done by mapping the request path to a file: If you request www.example.org/test.php, the web server will actually look for a file named test.php in a pre-defined directory.
There is a feature that comes in handy for our purpose: Many web servers also allow you to call www.example.org/test.php/hello and it will still execute test.php. PHP makes the additional stuff in the requested path accessible via the $_SERVER['PATH_INFO']
variable. In this case it would contain "/hello".
Using this, we 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);
?>
For the sake of simplicity, I did not make the router a class. But from here on, that shouldn't be a problem either.
Let's assume we named this file index.php. We can now call www.example.org/index.php/hello to get a nice "Hello, World!" message. Or www.example.org/index.php/ to get the main page.
The "index.php" in that URL is still ugly, but we can fix this by using URL rewriting. In Apache HTTPD you would put a .htaccess
file in the same directory with the following content:
RewriteEngine on
RewriteRule ^(.*)$ index.php/$1
And there you are! Your very own router with under 10 lines of logic code (not counting comments and the routes list).
Solution 2
Well... there are many framework in internet for php routing. If you want you can try that from https://packagist.org/search/?q=route. But to be honest, if you are from procedural PHP world, it could be problematic for you first time.
If you like, you can use following code written by Jesse Boyer that I used to for my own projects. You application structure should follows-
[Application-folder]
- index.php
- .htaccess
- route.php
route.php
<?php
/**
* @author Jesse Boyer <[email protected]>
* @copyright Copyright (C), 2011-12 Jesse Boyer
* @license GNU General Public License 3 (http://www.gnu.org/licenses/)
* Refer to the LICENSE file distributed within the package.
*
* @link http://jream.com
*
* @internal Inspired by Klein @ https://github.com/chriso/klein.php
*/
class Route
{
/**
* @var array $_listUri List of URI's to match against
*/
private static $_listUri = array();
/**
* @var array $_listCall List of closures to call
*/
private static $_listCall = array();
/**
* @var string $_trim Class-wide items to clean
*/
private static $_trim = '/\^$';
/**
* add - Adds a URI and Function to the two lists
*
* @param string $uri A path such as about/system
* @param object $function An anonymous function
*/
static public function add($uri, $function)
{
$uri = trim($uri, self::$_trim);
self::$_listUri[] = $uri;
self::$_listCall[] = $function;
}
/**
* submit - Looks for a match for the URI and runs the related function
*/
static public function submit()
{
$uri = isset($_REQUEST['uri']) ? $_REQUEST['uri'] : '/';
$uri = trim($uri, self::$_trim);
$replacementValues = array();
/**
* List through the stored URI's
*/
foreach (self::$_listUri as $listKey => $listUri)
{
/**
* See if there is a match
*/
if (preg_match("#^$listUri$#", $uri))
{
/**
* Replace the values
*/
$realUri = explode('/', $uri);
$fakeUri = explode('/', $listUri);
/**
* Gather the .+ values with the real values in the URI
*/
foreach ($fakeUri as $key => $value)
{
if ($value == '.+')
{
$replacementValues[] = $realUri[$key];
}
}
/**
* Pass an array for arguments
*/
call_user_func_array(self::$_listCall[$listKey], $replacementValues);
}
}
}
}
.htaccess
here in 2nd line, instead of '/php/cfc/' you need to put your localhost project directory name, such as 'Application-folder'
RewriteEngine On
RewriteBase /php/cfc/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?uri=$1 [QSA,L]
index.php
In index.php file, you need to write following codes-
<?php
include "route.php";
/**
* -----------------------------------------------
* PHP Route Things
* -----------------------------------------------
*/
//define your route. This is main page route. for example www.example.com
Route::add('/', function(){
//define which page you want to display while user hit main page.
include('myindex.php');
});
// route for www.example.com/join
Route::add('/join', function(){
include('join.php');
});
Route::add('/login', function(){
include('login.php');
});
Route::add('/forget', function(){
include('forget.php');
});
Route::add('/logout', function(){
include('logout.php');
});
//method for execution routes
Route::submit();
This things work perfectly for me. Hope it will work for you too...
Happy Coding... :)
Related videos on Youtube
Stephan-v
Hi there I love programming, designing and coming up with fresh new ideas. My goto programming framework is Laravel complemented with Vue.js. I'm a quick learner and I love getting up to date on the latest technology. Helping people out with their programming conundrums is something I love to do.
Updated on June 04, 2022Comments
-
Stephan-v almost 2 years
I'm looking for a tutorial or explaination on how to do very basic php routing.
For example when I visit a link like: mywebsite.com/users I want to run the get method of a route class to provide the data, in the same way laravel does it.
Route::get('users', function() { return 'Users!'; });
Can somebody explain how to do this or provide me with some more information?
-
cHao over 10 yearsAbsolute bare-bones simplest thing that could possibly work? See if the route string is a substring of the URL being requested. If so, call the function.
-
Brad over 10 yearsThere are lots of ways to do this. If you want this behavior automatically, use a framework that provides it. PHP itself does not include such a framework.
-
amarjit singh over 10 yearsyou can achieve this by .htaccess file as well if you are not familiar with the frameworks.
-
Denis de Bernardy over 10 yearsPart of the benefit of open source software is that you can, well, read the source code...
-
Stephan-v over 10 yearsTrue but it goes a little bit above my head though when the documentation jumps from one method to another.
-
Jake Wilson over 10 yearsI would look through the Laravel 3 source code for how it internally handles routing. L3's source is a bit more straightforward than L4.
-
-
Stephan-v over 10 yearsThere is a feature that comes in handy for our purpose: Many web servers also allow you to call www.example.org/test.php/hello and it will still execute test.php How is this part done though, this is one of the most important steps.
-
hanzi over 10 yearsThat works out of the box. Just put a PHP file with
<?php echo $_SERVER['PATH_INFO']; ?>
somewhere and try it yourself. -
Admin over 2 yearsAs it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-
BudwiseЯ over 2 yearsWhile this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review