User-based Directory Validation

2011-01-19

Restricting file paths

Disclaimer: This can be worked around, especially if a user has access to your PHP code and can override your validation method (the class this method originated in was being given to users). I mostly wrote it because it was a fun way to use some of the more obscure PHP functions. Moving on.

/**
 * This uses some file system trickery to try and ensure that any
 * directories the user tries to use are inside their own home directory.
 * It's not real security since this method can be changed, but it might
 * help stop someone from doing something stupid accidentally.
 *
 * @param string $dir File path to check
 * @return boolean
 */
protected function isValidDir($dir)
{
    //get array of info about current file owner
    $homeDir = posix_getpwuid(fileowner('.'));
    //get their home directory
    $homeDir = $homeDir['dir'];
    //make sure $dir's absolute path starts in their home dir
    if (0 === strpos(realpath($dir), $homeDir['dir'])) {
        return true;
    } else {
        return false;
    }
}

Tags: php