Over a million developers have joined DZone.

Canonical Path

DZone's Guide to

Canonical Path

Free Resource
This function transforms an HTTP request path (ie, $_SERVER['PATH_INFO']) into its canonical form, removing empty path elements and relative path elements (//, /./, /../). It assumes that there is a trailing slash on the path if it's a directory.

function canonical_path($path) {
    $canonical = preg_replace('|/\.?(?=/)|','',$path);
    while (($collapsed = preg_replace('|/[^/]+/\.\./|','/',$canonical,1)) !== $canonical) {
        $canonical = $collapsed;
    $canonical = preg_replace('|^/\.\./|','/',$canonical);
    return $canonical;

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}