替换 PHP 的 realpath()
显然,realpath
有很多问题.在 PHP 5.3.1 中,它会导致随机崩溃.在 5.3.0 及更低版本中,realpath
随机失败并返回 false(当然对于相同的字符串),而且它总是在 realpath
上失败 - 两次/多次使用相同的字符串(当然,它第一次就起作用了).
Apparently, realpath
is very buggy. In PHP 5.3.1, it causes random crashes.
In 5.3.0 and less, realpath
randomly fails and returns false (for the same string of course), plus it always fails on realpath
-ing the same string twice/more (and of course, it works the first time).
此外,它在早期的 PHP 版本中存在很多问题,以至于完全无法使用.嗯......它已经是,因为它不一致.
Also, it is so buggy in earlier PHP versions, that it is completely unusable. Well...it already is, since it's not consistent.
无论如何,我有哪些选择?也许我自己重写?这是可取的吗?
Anyhow, what options do I have? Maybe rewrite it by myself? Is this advisable?
推荐答案
感谢 Sven Arduwie 的代码(由 Pekka 指出) 和一些修改,我已经构建了一个(希望)更好的实现:
Thanks to Sven Arduwie's code (pointed out by Pekka) and some modification, I've built a (hopefully) better implementation:
/**
* This function is to replace PHP's extremely buggy realpath().
* @param string The original path, can be relative etc.
* @return string The resolved path, it might not exist.
*/
function truepath($path){
// whether $path is unix or not
$unipath=strlen($path)==0 || $path{0}!='/';
// attempts to detect if path is relative in which case, add cwd
if(strpos($path,':')===false && $unipath)
$path=getcwd().DIRECTORY_SEPARATOR.$path;
// resolve path parts (single dot, double dot and double delimiters)
$path = str_replace(array('/', '\'), DIRECTORY_SEPARATOR, $path);
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
$absolutes = array();
foreach ($parts as $part) {
if ('.' == $part) continue;
if ('..' == $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
$path=implode(DIRECTORY_SEPARATOR, $absolutes);
// resolve any symlinks
if(file_exists($path) && linkinfo($path)>0)$path=readlink($path);
// put initial separator that could have been lost
$path=!$unipath ? '/'.$path : $path;
return $path;
}
注意: 与 PHP 的 realpath
不同,此函数不会在出错时返回 false;它返回一条尽可能解决这些怪癖的路径.
NB: Unlike PHP's realpath
, this function does not return false on error; it returns a path which is as far as it could to resolving these quirks.
注意 2: 显然有些人无法正确阅读.Truepath() 不适用于网络资源,包括 UNC 和 URL.它仅适用于本地文件系统.
Note 2: Apparently some people can't read properly. Truepath() does not work on network resources including UNC and URLs. It works for the local file system only.
相关文章