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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}