gpt4 book ai didi

php - 解析不存在文件的相对路径(如真实路径)的最佳方法是什么?

转载 作者:IT王子 更新时间:2023-10-29 00:12:46 25 4
gpt4 key购买 nike

我正在尝试在文件系统抽象中强制执行根目录。我遇到的问题如下:

API 让您可以读写文件,不仅可以读写本地存储,还可以读写远程存储。因此,幕后正在进行各种规范化。目前它不支持相对路径,所以这样的事情是不可能的:

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

我希望能够安全地解析路径,以便输出为:path/to/relative/file.txt。正如为此错误/增强创建的 github 问题 (https://github.com/FrenkyNet/Flysystem/issues/36#issuecomment-30319406) 中所述,它需要做的不仅仅是拆分段并相应地删除它们。

另外,由于包处理远程文件系统和不存在的文件,realpath 是不可能的。

那么,在处理这些路径时应该如何处理呢?

最佳答案

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

关于php - 解析不存在文件的相对路径(如真实路径)的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20522605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com