Question

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?

Was it helpful?

Solution

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).

OTHER TIPS

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 <contact@jream.com>
 * @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... :)

Well, its possible to make a PHP Routing system in native PHP by using

  • native PHP (no laravel)
  • .htaccess

This shows how to setup a php routing system in a few mins: https://www.youtube.com/watch?v=ysnW2mRbZjE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top