验证用户输入的文件\获取\内容PHP
在我的php文件中,我使用$\u GET参数在我的服务器上打开一个文件,如下所示:验证用户输入的文件\获取\内容PHP,php,security,file-get-contents,Php,Security,File Get Contents,在我的php文件中,我使用$\u GET参数在我的服务器上打开一个文件,如下所示: $filename = $_GET["filename"]; $content = file_get_contents("/path_to_files/".$filename); 我的问题是,如何使其更安全,以便用户无法访问服务器上父文件夹中的文件?这是我需要在服务器上执行的操作,例如权限和/或配置吗?还是应该在我的php文件中验证$filename? 提前谢谢 我认为您不必对服务器上的权限做什么,因为实际上是
$filename = $_GET["filename"];
$content = file_get_contents("/path_to_files/".$filename);
我的问题是,如何使其更安全,以便用户无法访问服务器上父文件夹中的文件?这是我需要在服务器上执行的操作,例如权限和/或配置吗?还是应该在我的php文件中验证$filename?
提前谢谢 我认为您不必对服务器上的权限做什么,因为实际上是php访问文件,而不是用户 您可以将$filename与文件白名单进行核对。
你能提供更多关于你要做什么的信息吗?最安全的方法是在使用文件路径时避免使用外部参数。。 您可以实现如下内容:
$files = array (
'file1' => 'path/to/file1.php',
'file2' => 'path/to/file2.php',
'file3' => 'path/to/file3.php',
...
);
if ( in_array($_GET['file'], array_keys($files) ) )
{
$content = file_get_contents($files[$GET['file']]);
}
否则。。。从这里检查方法:
最好是为允许的文件设置白名单 你可以有类似文件名模式的东西, [姓名][点][分机]
if (!preg_match('/^[a-zA-Z0-9_-]+\.[a-zA-Z0-9]+$/', $filename) {
throw new Exception('file not allowed');
}
但这样,用户可以访问/path_to_files/目录中的所有文件您发布的方法不是一种非常安全的方法,您应该考虑更改它 如果需要使用此方法,请对脚本进行以下更改
$filename = basename($_GET["filename"]);
$content = file_get_contents("/path_to_files/".$filename, false);
file_get_contents函数中的false参数只会在您提供的路径中查找文件,而不会在其他位置查找文件。白名单似乎是最安全的方法,但您可以使用这样的脚本
$file = realpath("/path_to_files/" . $_GET['filename']);
// Check that $file is actually in the specified path
if(substr($file, 0, strlen("/path_to_files/")) == "/path_to_files/"){
include($file);
}
但我不知道是否有可能愚弄realpath…看起来“白名单”是一条出路。谢谢你的好例子,正是我需要的。谢谢你的反馈。基本上,我只是读取一个给定的html文件并将其输出为html。因为我有一个预先确定的可以输出的文件列表,所以我认为白名单方法会很好地工作。你有没有办法给我提供一个链接来解释这个假参数?谢谢