[フレーム]
Last Updated: May 16, 2021
·
22.06K
· 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

Very smart!

over 1 year ago ·

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 ·

Thanks. You approach really makes sense...

over 1 year ago ·

AltStyle によって変換されたページ (->オリジナル) /