gdam2w
Last Updated: February 25, 2016
·
7.526K
· otar
F898b4e1ba5b8ed93f643859b9d55cd6

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]
Say Thanks
Respond

3 Responses
Add your response

7286
B04097e704cd0cdc718094f25acefe27

Very smart!

over 1 year ago ·
7588
1101eb0f7418b3206f90211aa61e9a21

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
F898b4e1ba5b8ed93f643859b9d55cd6

Thanks. You approach really makes sense...

over 1 year ago ·