How to check if file path is located in a path

I would like to check if a user specified file path is located inside another path:

Example
user supplied path: /home/data/images/file1.jpg
allowed location: /home/data/images

I can compare the beginning of string, but user may enter different combination like /home/data/images/…/…/otherfile.jpg

I there a simple way in PHP?

Think simpler :slight_smile:

Why not just check the input filename for invalid input?

function validatePath($Path){
    return (strpos($Path, '/') !== false);
}

If you do want to verify the overall path, use realpath() on the directory, and check if the initial directory is in that path:


function validatePath($Path){
    $Directory = '/home/data/images/';
    $FilePath = $Directory . $Path;
    return (substr($FilePath, 0, strlen($Directory)) == $Directory);
}

Thank you, I didn’t notice there is function realpath().