The basics of php routing

后端 未结 3 829
执念已碎
执念已碎 2020-12-11 12:32

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 meth

3条回答
  •  鱼传尺愫
    2020-12-11 12:53

    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:

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

提交回复
热议问题