script.php
$filename = realpath(sprintf("%s/%s", getcwd(), $argv[1]));
var_dump($filename);
让我们试试
[/foo/bar/bof] $ php script.php ../foo.txt
string(16) "/foo/bar/foo.txt"
[/foo/bar/bof] $ php script.php ../nonexistent.txt
bool(false)
该死!realpath
返回false,因为该文件不存在。
我想为../nonexistent.txt
看到的是
string(24) "/foo/bar/nonexistent.txt"
如何获得PHP中任何相对路径的规范化路径
注意:我看到了一些关于解决符号链接路径的问题。这些问题的答案不适用于我的问题。
这是我能想到的最好的
function canonicalize_path($path, $cwd=null) {
// don't prefix absolute paths
if (substr($path, 0, 1) === "/") {
$filename = $path;
}
// prefix relative path with $root
else {
$root = is_null($cwd) ? getcwd() : $cwd;
$filename = sprintf("%s/%s", $root, $path);
}
// get realpath of dirname
$dirname = dirname($filename);
$canonical = realpath($dirname);
// trigger error if $dirname is nonexistent
if ($canonical === false) {
trigger_error(sprintf("Directory `%s' does not exist", $dirname), E_USER_ERROR);
}
// prevent double slash "//" below
if ($canonical === "/") $canonical = null;
// return canonicalized path
return sprintf("%s/%s", $canonical, basename($filename));
}
它要求路径中的所有目录都存在。路径的basename
是唯一不存在的部分。
如果目录名不存在,将引发错误。
我创建了这个:
$path_canonicalize = function($str, $started = false) use(&$path_canonicalize)
{
$str = str_replace('/', DIRECTORY_SEPARATOR, $str).DIRECTORY_SEPARATOR;
if (!$started)
$str = preg_replace("/".preg_quote(DIRECTORY_SEPARATOR, "'".DIRECTORY_SEPARATOR."'")."{2,}/", DIRECTORY_SEPARATOR, $str);
$pos = strpos($str, '..'.DIRECTORY_SEPARATOR);
if ($pos !== false)
{
$part = trim(substr($str, 0, $pos), DIRECTORY_SEPARATOR);
$str = $path_canonicalize(trim(substr($part, 0, strrpos($part, DIRECTORY_SEPARATOR)), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.trim(substr($str, $pos+3), DIRECTORY_SEPARATOR), true);
}
return rtrim($str, DIRECTORY_SEPARATOR);
};
/*
Try those cases to check the consistency:
$str = __DIR__.'/template//////../header//..';
$str = __DIR__.'/template///..///../header//..';
$str = __DIR__.'/template/../header/..';
$str = __DIR__.'/template/../header/../';
$str = __DIR__.'/template/../header/..//';
$str = __DIR__.'/template/../header/..///';
$str = __DIR__.'/template/../header/..///..';
$str = __DIR__.'/template/../header/..///../';
$str = __DIR__.'/template''..''header''..';
*/
$str = __DIR__.'/template/../header/..///..//';
echo 'original: '.$str.PHP_EOL;
echo 'normalized: '.$path_canonicalize($str).PHP_EOL;
一些问题:
- 例程不检查给定路径是相对路径还是绝对路径
- 建议告知绝对路径,但也适用于相对路径。例程将所有内容都视为字符串,而不是文件系统
- 最终结果将删除字符串开头和结尾的目录分隔符
- 不支持单点
./
或/.