php目录遍历问题

时间:2011-05-22 01:35:21

标签: php security

您好 我们有一些使用file_get_contents()函数的php代码,我知道这很容易受到针对恶意的traversel攻击。给出以下代码:

$mydata=$_GET['thefile'];
$data = file_get_contents ('/var/html'.$file);
echo $data

如何进行一些简单的输入过滤,以便通过玩弄我的输入来阻止某人可能进行目录遍历的可能性?

/ MR

2 个答案:

答案 0 :(得分:3)

您想要basename

$mydata = basename(realpath($_GET['thefile']));

附加(略微修改)你的例子:

$file=$_GET['thefile']; 
$mypath='/var/www/';
$location= basename(realpath($mypath.$file));
$data = file_get_contents($location);
echo $data;

注意......虽然这会进行一定程度的错误检查,但它不会进行错误处理。我会把它留给你。

答案 1 :(得分:1)

如果$_GET['thefile']不使用“images / fileX.jpg”等文件夹,您可以使用basename()

$filename = basename($_GET['thefile']);
readfile('/var/html/'.$filename);

当'../../passwords.txt'作为$_GET['thefile']时,它将被basename转换为'passwords.txt'。
在基本名称中添加realpath()不会添加任何安全性。

如果您的脚本确实需要支持子目录,那么使用realpath()来确定它是否在'/ var / html'目录中。

$baseDir = realpath('/var/html/'); // (mayby /var/html is a symlink)
$baseDirLength = strlen($baseDir);
$filepath = realpath('/var/html/'.$_GET['thefile']);
if (substr($filepath, 0, $baseDirLength) == $baseDir) {
   // Even when all the '../' in the thefile are resolved 
   // the path is within the $baseDir
} else {
  // invalid $_GET['thefile']
}