I am trying to create a function that blocks access to some of my low-level directories. For example, when creating my site, I do not want the downloads to be loaded below / var / www / html / site / uploads / if I am mistaken in the encoding. It will also help prevent a typo to delete a directory when deleting cache files or something else.
This is easy to do with realpath () and strcasecmp ().
The problem is that I cannot use realpath () to generate an absolute path, because any calls to this function with missing directories return FALSE. Below is my best attempt to take a look at the paths to test them.
function is_sub_dir($path = NULL, $parent_folder = NULL) { //Convert both to real paths //Fails if they both don't exist //$path = realpath($path); //$parent_folder = realpath($parent_folder); //Neither path is valid if( !$path OR !$parent_folder ) { return FALSE; } //Standarize the paths $path = str_replace('\\', '/', $path); $parent_folder = str_replace('\\', '/', $parent_folder); //Any evil parent directory requests? if(strpos($path, '/..') !== FALSE) { return FALSE; } //If the path is greater if( strcasecmp($path, $parent_folder) > 0 ) { return $path; } return FALSE; } //BAD FOLDER!!! var_dump(is_sub_dir('/var/www/html/site/uploads/../', '/var/www/html/site/uploads/'));
Does anyone know how to correctly put file path blocks in place to protect against access to low level folders?
: UPDATE:
I want to clarify again that this verification method will be used on several severs, as well as when creating directories that are above a given directory.
For example, in my uploads directory, I want to allow administrators to create new auxiliary directories, such as ... uploads / sub / . Based on a reliable way to ensure that the specified directory is really above the parent directory - I can feel more secure by allowing my administrators to work with the file system in the uploads folder.
Since I may need to verify that uploads / sub is higher than uploads / , before I create it, I cannot use realpath () because uploads / sub no longer exists.
As for the actual location of the uploads folder, which appears on the fly PHP.
define('UPLOAD_PATH', realpath(dirname(__FILE__)));
: UPDATE 2:
I have an idea that if I should use realpath to compare the whole path minus the last directory segment. Then even if this last segment of the directory still needs to be created - could the rest of the path be forced to map to the minimum parent directory?