2

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 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Nice. Seems like you can skip the file_exists though: realpath() returns FALSE on failure, e.g. if the file does not exist.
Also not sure that link checking is necessary in my case, since they would have to be created in that directory first?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.