在没有realpath()的情况下清理PHP中的文件路径 [英] Sanitize file path in PHP without realpath()

查看:90
本文介绍了在没有realpath()的情况下清理PHP中的文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在不使用realpath()的情况下安全地清理路径输入?

Is there a way to safely sanitize path input, without using realpath()?

目标是防止像../../../../../path/to/file

 $handle = fopen($path . '/' . $filename, 'r');

推荐答案

不确定为什么您不想使用realpath,但是路径名清除是一个非常简单的概念,如下所示行:

Not sure why you wouldn't want to use realpath but path name sanitisation is a very simple concept, along the following lines:

  • 如果路径是相对路径(不是以/开头),请在路径前添加当前工作目录和/,使其成为绝对路径.
  • 用一个(a)替换一个以上/的所有序列.
  • 将所有出现的/./替换为/.
  • 如果最后删除/..
  • /替换/anything/../.
  • 如果最后删除/anything/...
  • If the path is relative (does not start with /), prefix it with the current working directory and /, making it an absolute path.
  • Replace all sequences of more than one / with a single one (a).
  • Replace all occurrences of /./ with /.
  • Remove /. if at the end.
  • Replace /anything/../ with /.
  • Remove /anything/.. if at the end.

在这种情况下,文本anything表示不是/的最长字符序列.

The text anything in this case means the longest sequence of characters that aren't /.

请注意,应持续应用这些规则,直到没有一个规则导致更改为止.换句话说,完成全部六个操作(一次通过).如果字符串更改,请返回并再次执行所有六个操作(另一遍操作).继续这样做,直到字符串与刚刚执行传递之前的字符串相同为止.

Note that those rules should be applied continuously until such time as none of them result in a change. In other words, do all six (one pass). If the string changed, then go back and do all six again (another pass). Keep doing that until the string is the same as before the pass just executed.

完成这些步骤后,您便拥有了可以检查有效模式的规范路径名.很有可能是不是以../开头的任何内容(换句话说,它不会尝试移至起点之上.您可能要应用其他规则,但这不在此问题的范围之内.

Once those steps are done, you have a canonical path name that can be checked for a valid pattern. Most likely that will be anything that doesn't start with ../ (in other words, it doesn't try to move above the starting point. There may be other rules you want to apply but that's outside the scope of this question.

(a)如果您正在使用将路径开头的//视为特殊字符的系统,请确保在开头将多个/字符替换为两个.这是POSIX唯一允许(但不要求)对倍数进行特殊处理的地方,在所有其他情况下,多个/字符等效于单个字符.

(a) If you're working on a system that treats // at the start of a path as special, make sure you replace multiple / characters at the start with two of them. This is the only place where POSIX allows (but does not mandate) special handling for multiples, in all other cases, multiple / characters are equivalent to a single one.

这篇关于在没有realpath()的情况下清理PHP中的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆