Something like this should work:
function isBelowAllowedPath($file, $allowedPath)
{
return ( strpos( realpath($file), $allowedPath) === 0 );
}
isBelowAllowedPath('/etc/passwd', '/var/www/pub/'); // false
isBelowAllowedPath('/var/www/pub/index.htm', '/var/www/pub/'); // true
or if you want to make sure $file is there as well
function isBelowAllowedPath($file, $allowedPath)
{
return file_exists( $allowedPath . basename(realpath($file)) );
}
isBelowAllowedPath('/../../../../etc/passwd', '/var/www/pub/'); // false
isBelowAllowedPath('index.htm', '/var/www/pub/'); // true
or if you want $file to be in a specific list of $allowedPaths (not below a path)
function isInAllowedPath($file, array $allowedPath)
{
$fileDir = realpath(dirname($file));
return (in_array($fileDir, $allowedPath));
}
$allowed = array('/var/www/pub/', 'somewhere/else');
isInAllowedPath('/var/www/pub/foo/index.htm', $allowed); // false
isInAllowedPath('/var/www/pub/index.htm', $allowed); // true