views:

17

answers:

1

I get a file path to a user file and I want to make sure that this path is to a valid existing user file and not to something bogus or a system file or something like that.

I know I can use file_exists to check that it exists, but I'm not sure how I should make sure that the file is in a certain sub-directory...

+1  A: 

You should be aware of hard links and symbolic links. If you're going to change the file, do a stat to check if it's a regular file and its node count is 1.

$subdirToCheck = "/home/mysubdir/";
$file = "relativepath/userfile";
$absfile = realpath($file);
if ($absfile !== FALSE && file_exists($absfile) &&
        substr($absfile, 0, strlen($subdirToCheck)) == $subdirToCheck) {
    $ls = lstat($absfile);
    if (is_link($ls) || $ls["nlink"] > 1) {
        //abort
    }
    else {
        //do stuff
    }
}
Artefacto
Nice. Seems like you can skip the file_exists though: *realpath() returns FALSE on failure, e.g. if the file does not exist.*
Svish
Also not sure that link checking is necessary in my case, since they would have to be created in that directory first?
Svish
@Svish Yes, but see the changelog. As to your other point, if you can guarantee that the directory and its subdirectories do not contain symlinks, you can obviously skip the check.
Artefacto