PHP:防止文件夹黑客攻击 - 如果路径中有../?

mat*_*att 7 php path

我在php中做了一个简单的事情,我想知道如何测试变量$ path是否包含以下结构../

所以我在我的网址中只有一个?path = somepath结构,如果有人进入../它允许他进入一个目录.我当然知道这不是最好的解决方案,但是对于我的小东西来说,如果我只是在其中测试一个"../"字符串的$ path变量就足够了.如果是这样死();

我不确定测试它的最佳方法是什么!

关于亚光

Dan*_*erg 12

你可以直接调用realpath()它并检查它应该存在的路径是否是它的前缀,而不是这样做.

更好的是,为什么不保留白名单并拒绝任何不在其中的东西?


oez*_*ezi 2

回答你的问题:

if(strpos($path,'../') !== false){
  // looks like someone 's trying to hack here - simply
  // do nothing (or send an email-notification to yourself
  // to be informed and see how often this happens)
}else{
  // here comes the magic

}
Run Code Online (Sandbox Code Playgroud)

但是:你真的不应该这样做。如果您想要一个简单的解决方案,请对每个可能的 $path 使用 switch 语句并包含相关文件(或您必须执行的任何操作)。