Zerbu
Zerbu

Reputation: 585

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

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

Answers (2)

Geoffrey
Geoffrey

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

devanand
devanand

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

Related Questions