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


How do you check if a file is in a certain directory using PHP?

在PHP中访问文件时,可以使用".."从目录中转义,这可能会导致安全风险。有什么方法可以验证文件是否在指定的目录中?它似乎没有内置功能。

这不是检查文件是否存在于预期位置的安全方法。。你应该做以下事情。

$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';
}

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";
}
?>