1

In PHP, is there a built-in way to resolve a path relative to another?

For example, given a $baseDir dir: /home/ben/project, the following $path should resolve to:

  • /foo/bar/foo/bar
  • ../foo/bar, → /home/ben/foo/bar

Solutions that come to mind:

  • Temporarily changing the current working directory, and using realpath():

    $currentDir = getcwd();
    chdir($baseDir);
    $resolvedPath = realpath($path);
    chdir($currentDir);
    
    return $resolvedPath;
    

    This solution is a bit tedious.

  • Checking if the path is absolute, if not, using realpath():

    if ($path[0] === '/') {
        return $path;
    }
    
    return realpath($currentDir . '/' . $path);
    

    This solution is not cross-platform; making it safely cross-platform may not be as trivial as it looks.

Last but not least, realpath() returns false when the path does not exist, which is not taken into account in the above codes, and may be a problem in some use cases.

Did I miss something?

BenMorel
  • 34,448
  • 50
  • 182
  • 322

0 Answers0