验证file_get_contents PHP的用户输入

Nei*_*low 0 php security file-get-contents

在我的php文件中,我使用$ _GET参数在我的服务器上打开一个文件,如下所示:

$filename = $_GET["filename"];
$content = file_get_contents("/path_to_files/".$filename);
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何使这更安全,以便用户无法访问服务器上父文件夹中的文件?这是我需要在服务器上执行的操作,例如权限和/或配置吗?或者应该$filename在我的php文件中验证?提前致谢!

lu *_*cip 5

最安全的方法是在使用文件路径时避免使用外部参数..您可以实现以下内容:

$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']]);
}
Run Code Online (Sandbox Code Playgroud)

否则......从这里检查方法: 文件名的字符串清理程序