Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用PHP检查文件是否位于某个目录中?_Php_Directory_Dir - Fatal编程技术网

如何使用PHP检查文件是否位于某个目录中?

如何使用PHP检查文件是否位于某个目录中?,php,directory,dir,Php,Directory,Dir,在PHP中访问文件时,可以使用“.”从目录中转义,这可能导致安全风险。是否有任何方法可以验证文件是否位于指定目录中?它似乎没有内置函数。在php.net上有一个非常好的例子 这不是检查文件是否存在于预期位置的安全方法。。您应该执行以下操作 $base = '/expected/path/'; $filename = realpath($filename); if ($filename === false || strncmp($filename, $base, strlen($base

在PHP中访问文件时,可以使用“.”从目录中转义,这可能导致安全风险。是否有任何方法可以验证文件是否位于指定目录中?它似乎没有内置函数。

在php.net上有一个非常好的例子


这不是检查文件是否存在于预期位置的安全方法。。您应该执行以下操作

$base     = '/expected/path/';
$filename = realpath($filename);
if ($filename === false || strncmp($filename, $base, strlen($base)) !== 0) {
    echo 'Missing file or not in the expected location';
}
else {
    echo 'The file exists and is in the expected location';
}

-1因为您没有说明如何防止在输入路径中出现“.”。我还将使用realpath()命令删除$base文件夹,以确保斜杠在同一方向对齐。这会增加额外的开销。如果您担心斜杠方向,只需使用PHP定义
目录\u分隔符
$base     = '/expected/path/';
$filename = realpath($filename);
if ($filename === false || strncmp($filename, $base, strlen($base)) !== 0) {
    echo 'Missing file or not in the expected location';
}
else {
    echo 'The file exists and is in the expected location';
}