DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Canonical Path

04.17.2005
| 8674 views |
  • submit to reddit
        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;
}