PHP有一个很好的realpath()
函数,它可以将/dir1/dir2/../dir3/filename
之类的内容转换为/dir1/dir3/filename
。这个函数的“问题”是,如果/dir1/dir3/filename
不是实际文件而只是链接到另一个文件,PHP将遵循该链接并返回实际文件的真实路径。
但是,我实际上需要获得链接本身的真实路径。我所需要的只是解决路径中/dir/..
之类的复杂问题。我该怎么办?
答案 0 :(得分:1)
为您的要求写了一个函数。
function realpath_no_follow_link($str) {
if (is_link($str)) {
$pathinfo = pathinfo($str);
return realpath_no_follow_link($pathinfo['dirname']) . '/' .$pathinfo['basename'];
}
return realpath($str);
}
答案 1 :(得分:0)
我希望找到一个现有的PHP函数来做到这一点,或者根据xdazz的答案(但实际上我会按照我想要的方式工作)。找不到这样的答案,我写了自己的脏功能。我很高兴听到您的意见和改进建议!
// return the contracted path (e.g. '/dir1/dir2/../dir3/filename' => '/dir1/dir3/filename')
// $path: an absolute or relative path
// $rel: the base $path is given relatively to - if $path is a relative path; NULL would take the current working directory as base
// return: the contracted path, or FALSE if $path is invalid
function contract_path($path, $rel = NULL) {
if($path == '') return FALSE;
if($path == '/') return '/';
if($path[strlen($path) - 1] == '/') $path = substr($path, 0, strlen($path) - 1); // strip trailing slash
if($path[0] != '/') { // if $path is a relative path
if(is_null($rel)) $rel = getcwd();
if($rel[strlen($rel) - 1] != '/') $rel .= '/';
$path = $rel . $path;
}
$comps = explode('/', substr($path, 1)); // strip initial slash and extract path components
$res = Array();
foreach($comps as $comp) {
if($comp == '') return FALSE; // double slash - invalid path
if($comp == '..') {
if(count($res) == 0) return FALSE; // parent directory of root - invalid path
array_pop($res);
}
elseif($comp != '.') $res[] = $comp;
}
return '/' . implode('/', $res);
}
答案 2 :(得分:-3)
你可以试试abspath()函数。