Reputation: 585
When accessing a file in PHP, it's possible to escape from the directory using ".." which can lead to a security risk. Is there any way to validate that a file is in a specified directory? There doesn't seem to be a built-in function for it.
Upvotes: 3
Views: 3390
Reputation: 11353
This is not a secure way to check if the file exists in the expected location.. you should do the following.
$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';
}
Upvotes: 7
Reputation: 5290
There is a very good example on 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";
}
?>
Upvotes: -4