防止/.. 用户输入 [英] prevent /.. user input
问题描述
我在一个文件夹中有一个 php 脚本(我称之为根文件夹).该脚本基本上可以列出该根文件夹的子文件夹中的所有文件.用户可以使用 GET 参数指定应该显示哪个子文件夹.
I have a php script in a folder (I call it the root folder). The script can basically list all files in subfolders of this root folder. The user can specify which subfolder should be displayed by using GET-parameters.
script.php?foo
会显示
<root folder>/foo/
和script.php?.bar将显示
and script.php?.bar would display the content of
<root folder>/.bar/
然而,用户也可以欺骗"并使用诸如 /..
之类的命令来显示他们无法看到的文件夹的内容.
However, users could also "cheat" and use commands like /..
to display the content of folders they souldn't be able to see.
例如用
script.php?/../..
用户可能会在文件夹层次结构中占据很高的位置.
the users could get very high in the folder hierarchy.
您知道如何防止用户进行此类作弊".
Do you have an idea how to prevent users of doing "cheats" like this.
为了简单起见,假设 GET 参数存储在 $searchStatement
中.
For reason of simplicity, let's say the GET-parameter is stored in $searchStatement
.
推荐答案
您可以使用 realpath
将相对路径解析为绝对路径,然后检查该路径是否以您的根"文件夹的路径:
You could use realpath
to resolve the relative path to an absolute one and then check if that path begins with your "root" folder's path:
$absolutePath = realpath(__DIR__ . '/' . trim($searchStatement, '/'));
if (strpos($absolutePath, __DIR__ .'/') !== 0) {
die('Access denied.');
}
这篇关于防止/.. 用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!