Reputation: 46040
How do I get the absolute path to a file, without following symlinks.
E.g.
/path/to/some/file
/path/to/some/link -> /path/to/some/file
/path/to/some/directory/
My current working directory is /path/to/some/directory/
and I go realpath('../link)
it returns /path/to/some/file
.
(I know realpath
is supposed to work this way)
Is there a function instead of realpath
that would return /path/to/some/link
Upvotes: 2
Views: 1855
Reputation: 15735
David Beck wrote a solution that cleans up the relative path components without accessing the actual file system in the comments section of the PHP manual. Alas, he forgot to add a return
statement to the function, but otherwise it seems to work great if this is what you need. Also works with URLs.
function canonicalize($address)
{
$address = explode('/', $address);
$keys = array_keys($address, '..');
foreach($keys AS $keypos => $key)
{
array_splice($address, $key - ($keypos * 2 + 1), 2);
}
$address = implode('/', $address);
$address = str_replace('./', '', $address);
return $address;
}
$url = '/path/to/some/weird/directory/../.././link';
echo canonicalize($url); // /path/to/some/link
Upvotes: 3
Reputation:
there's also getcwd();
which I use quite often. Syntactically simpler.
Upvotes: 2