I created this one:
$path_canonicalize = function($str, $started = false) use(&$path_canonicalize)
{
$str = str_replace('/', DIRECTORY_SEPARATOR, $str).DIRECTORY_SEPARATOR;
if (!$started)
$str = preg_replace("/".preg_quote(DIRECTORY_SEPARATOR, "'".DIRECTORY_SEPARATOR."'")."{2,}/", DIRECTORY_SEPARATOR, $str);
$pos = strpos($str, '..'.DIRECTORY_SEPARATOR);
if ($pos !== false)
{
$part = trim(substr($str, 0, $pos), DIRECTORY_SEPARATOR);
$str = $path_canonicalize(trim(substr($part, 0, strrpos($part, DIRECTORY_SEPARATOR)), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.trim(substr($str, $pos+3), DIRECTORY_SEPARATOR), true);
}
return rtrim($str, DIRECTORY_SEPARATOR);
};
/*
Try those cases to check the consistency:
$str = __DIR__.'/template//////../header//..';
$str = __DIR__.'/template///..///../header//..';
$str = __DIR__.'/template/../header/..';
$str = __DIR__.'/template/../header/../';
$str = __DIR__.'/template/../header/..//';
$str = __DIR__.'/template/../header/..///';
$str = __DIR__.'/template/../header/..///..';
$str = __DIR__.'/template/../header/..///../';
$str = __DIR__.'/template\\..\\header\\..';
*/
$str = __DIR__.'/template/../header/..///..//';
echo 'original: '.$str.PHP_EOL;
echo 'normalized: '.$path_canonicalize($str).PHP_EOL;
Some concerns:
- The routine do not check if the given path is relative or absolute.
- Recommended to inform the absolute path, however works for relative paths too. The routine treat all as string and not as filesystem.
- Final result removes the directory separator from the beginning and end of a string.
- Do not supports single dot
./
or /.