防止在PHP中遍历目录但允许路径 [英] Preventing Directory Traversal in PHP but allowing paths
问题描述
我有一个基本路径/whatever/foo/
I have a base path /whatever/foo/
和
$_GET['path']
应该相对于它.
但是如何在不允许遍历目录的情况下完成此操作(读取目录)?
However how do I accomplish this (reading the directory), without allowing directory traversal?
例如
/\.\.|\.\./
无法正确过滤.
推荐答案
好吧,一种选择是比较真实路径:
Well, one option would be to compare the real paths:
$basepath = '/foo/bar/baz/';
$realBase = realpath($basepath);
$userpath = $basepath . $_GET['path'];
$realUserPath = realpath($userpath);
if ($realUserPath === false || strpos($realUserPath, $realBase) !== 0) {
//Directory Traversal!
} else {
//Good path!
}
基本上, realpath()
会将提供的路径解析为实际的路径物理路径(解析符号链接,..
,.
,/
,//
等)...因此,如果实际用户路径不是以真实基本路径开头,则它试图进行遍历.请注意,realpath
的输出将不具有任何虚拟目录",例如.
或..
...
Basically, realpath()
will resolve the provided path to an actual hard physical path (resolving symlinks, ..
, .
, /
, //
, etc)... So if the real user path does not start with the real base path, it is trying to do a traversal. Note that the output of realpath
will not have any "virtual directories" such as .
or ..
...
这篇关于防止在PHP中遍历目录但允许路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!