Created
January 10, 2011 03:02
-
-
Save thsutton/772287 to your computer and use it in GitHub Desktop.
Normalise paths in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Normalise a file path string so that it can be checked safely. | |
* | |
* Attempt to avoid invalid encoding bugs by transcoding the path. Then | |
* remove any unnecessary path components including '.', '..' and ''. | |
* | |
* @param $path string | |
* The path to normalise. | |
* @param $encoding string | |
* The name of the path iconv() encoding. | |
* @return string | |
* The path, normalised. | |
*/ | |
function _normalise($path, $encoding="UTF-8") { | |
// Attempt to avoid path encoding problems. | |
$path = iconv($encoding, "$encoding//IGNORE//TRANSLIT", $path); | |
// Process the components | |
$parts = explode('/', $path); | |
$safe = array(); | |
foreach ($parts as $idx => $part) { | |
if (empty($part) || ('.' == $part)) { | |
continue; | |
} elseif ('..' == $part) { | |
array_pop($safe); | |
continue; | |
} else { | |
$safe[] = $part; | |
} | |
} | |
// Return the "clean" path | |
$path = implode(DIRECTORY_SEPARATOR, $safe); | |
return $path; | |
} |
Made some modifications on my fork to handle cases like 0, 0.0 and also keep initial root slash intact.
https://gist.github.com/jstonne/5124fae2af1fbc59f949
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please take care that empty() will return TRUE for a path segment with the value '0' and '0.0'.