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

时间:2012-08-05 13:15:53

标签: php directory dir

在PHP中访问文件时,可以使用“..”从目录中逃脱,这可能导致安全风险。有没有办法验证文件是否在指定的目录中?它似乎没有内置功能。<​​/ p>

2 个答案:

答案 0 :(得分:2)

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

$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 :(得分:-2)

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

http://php.net/manual/en/function.file-exists.php

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>