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

后端 未结 4 1985
Happy的楠姐
Happy的楠姐 2020-12-30 01:43

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

4条回答
  •  情歌与酒
    2020-12-30 02:24

    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);
    }
    

提交回复
热议问题