gdam2w
Last Updated: February 25, 2016
·
9.665K
· otar

Get request path in PHP for routing

Ever been in the pain of retrieving current URL of a request with plain PHP under different root domains or local environments (with strange paths)?

<?php

function request_path()
{
    $request_uri = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
    $script_name = explode('/', trim($_SERVER['SCRIPT_NAME'], '/'));
    $parts = array_diff_assoc($request_uri, $script_name);
    if (empty($parts))
    {
        return '/';
    }
    $path = implode('/', $parts);
    if (($position = strpos($path, '?')) !== FALSE)
    {
        $path = substr($path, 0, $position);
    }
    return $path;
}

Examples

Retrieves p/new from coderwall.com/p/new.

Or languages/PHP from github.com/languages/PHP.

What to use it for? Do some quick routing like this:

<?php

$routes = [
    '/' => function()
    {
        // home page callback
    },
    'about-us' => ...,
    'profile/edit' => ...
];

$path = request_path();

if (isset($routes[$path]) AND is_callable($routes[$path]))
{
    $routes[$path]();
}
else
{
    // show some fancy error page with nyan cat
}

.htaccess

RewriteEngine On
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

3 Responses
Add your response

7286

Very smart!

over 1 year ago ·
7588

This!. <3 u bro.
You can also replace the conditional to this function call: $path = parse_url($path, PHP_URL_PATH); It will remove the query strnig

over 1 year ago ·
7590

Thanks. You approach really makes sense...

over 1 year ago ·