PHP Realpath for None Existant Paths

If you want the functionality of realpath, to take a path containing relative elements such as /../ then this little function is exactly what you are looking for.

PHP’s built in realpath function will return false if the file or folder does not exist. Unfortunately when using complex paths then this can make debugging things a little complicated.

To resolve this simply use this function:

function normalizePath($path) {
    return array_reduce(explode('/', $path), create_function('$a, $b', '
			if($a === 0)
				$a = "/";

			if($b === "" || $b === ".")
				return $a;

			if($b === "..")
				return dirname($a);

			return preg_replace("/\/+/", "/", "$a/$b");
		'), 0);
}

For example:

$path = dirname(__FILE__) . '/../../../folder/';
$path = normalizePath($path);
echo $path; // /var/www/vhosts/domain.com/folder

Tags: phpfunctionpathtiprelativeabsoluterealpathformatnormalise