-
-
Save yansern/5124fae2af1fbc59f949 to your computer and use it in GitHub Desktop.
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 (($i>0 && trim($part)=="") || $part=='.') { | |
continue; | |
} elseif ('..' == $part) { | |
array_pop($safe); | |
continue; | |
} else { | |
$safe[] = $part; | |
} | |
} | |
// Return the "clean" path | |
$path = implode(DIRECTORY_SEPARATOR, $safe); | |
return $path; | |
} |
On line 25, $i
is not defined, I think you meant $idx
First test : ../common
=> common
It's Wrong...
28 if (null === array_pop($safe)) $safe[] = '';
34 if (count($safe) == 1) $safe[] = '';
fix 'common' example
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This also handles edge cases including 0, 0.0 and keeps initial root slash intact.