Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Normalise paths in PHP
<?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;
}
@Tuurlijk

This comment has been minimized.

Copy link

@Tuurlijk Tuurlijk commented Jan 23, 2014

Please take care that empty() will return TRUE for a path segment with the value '0' and '0.0'.

@yansern

This comment has been minimized.

Copy link

@yansern yansern commented Jun 5, 2014

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
You can’t perform that action at this time.