2

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

Petah
  • 45,477
  • 28
  • 157
  • 213
  • Assuming that PHP will properly handle `/path/to/some/directory/../link` I doubt that there is a function out there. I may be wrong, but your best bet would be to write your own. – tomsseisums Apr 03 '13 at 03:39
  • Is there a reason you can't use `__DIR__ . '/../link'`? – Ja͢ck Apr 03 '13 at 03:47
  • @Jack no because the path is not relative to the PHP file. – Petah Apr 03 '13 at 22:11

2 Answers2

3

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
Kaivosukeltaja
  • 15,541
  • 4
  • 40
  • 70
  • I have tried a similar function to this, but it does find the absolute path from a relative one (e.g. `../link` just returns `..`). – Petah Apr 03 '13 at 22:10
  • Works well but doesn't in cases when you have `../` in "multiple places". Example: `/path/to/some/weird/directory/../../../link../` or `/path/to/some/weird/directory/../../../link..` – Daniel Omine Jan 11 '16 at 08:33
2

there's also getcwd(); which I use quite often. Syntactically simpler.

  • `chdir($dir);echo getcwd();` this is far better than a user defined path resolution function. Thank you! – chiliNUT Nov 21 '14 at 15:58