What is the best way to resolve a relative path (like realpath) for non-existing files?

Viewed 9415

I'm trying to enforce a root directory in a filesystem abstraction. The problem I'm encountering is the following:

The API lets you read and write files, not only to local but also remote storages. So there's all kinds of normalisation going on under the hood. At the moment it doesn't support relative paths, so something like this isn't possible:

$filesystem->write('path/to/some/../relative/file.txt', 'file contents');

I want to be able to securely resolve the path so the output is would be: path/to/relative/file.txt. As is stated in a github issue which was created for this bug/enhancement (https://github.com/FrenkyNet/Flysystem/issues/36#issuecomment-30319406) , it needs to do more that just splitting up segments and removing them accordingly.

Also, since the package handles remote filesystems and non-existing files, realpath is out of the question.

So, how should one go about when dealing with these paths?

4 Answers

To quote Jame Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

protected function getAbsoluteFilename($filename) {
  $path = [];
  foreach(explode('/', $filename) as $part) {
    // ignore parts that have no value
    if (empty($part) || $part === '.') continue;

    if ($part !== '..') {
      // cool, we found a new part
      array_push($path, $part);
    }
    else if (count($path) > 0) {
      // going back up? sure
      array_pop($path);
    } else {
      // now, here we don't like
      throw new \Exception('Climbing above the root is not permitted.');
    }
  }

  // prepend my root directory
  array_unshift($path, $this->getPath());

  return join('/', $path);
}

./ current location

../ one level up

function normalize_path($str){
    $N = 0;
    $A =explode("/",preg_replace("/\/\.\//",'/',$str));  // remove current_location
    $B=[];
    for($i = sizeof($A)-1;$i>=0;--$i){
        if(trim($A[$i]) ===".."){
            $N++;
        }else{
            if($N>0){
                $N--;
            }
            else{
                $B[] = $A[$i];
            }
        }
    }
    return implode("/",array_reverse($B));
}

so:

"a/b/c/../../d" -> "a/d"
 "a/./b" -> "a/b"
Related