Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created January 10, 2011 03:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save thsutton/772287 to your computer and use it in GitHub Desktop.
Save thsutton/772287 to your computer and use it in GitHub Desktop.
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
Copy link

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

@yansern
Copy link

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