Recognizing the root dir in PHP
I'm wr开发者_开发知识库iting a PHP function that will delete all the files in the directory that's passed to it (and eventually, possibly expand it to a recursive delete). To be safe, I want to make sure that, through a bug or something, I don't try to delete anything if the directory passed in is the root directory.
File permissions should protect me to a large extent, but just in case, and especially if I expand it to a recursive delete I just want to take that extra step.
As a complicating factor, this code may be run in a windows machine or a linux machine, so the root directory may look like 'C:\' or '/'. I assume there are other ways that really refer to the root as well, possibly 'c:\temp..'
So, is there a reliable way in PHP to recognize that a dir spec resolves to the root of the file system?
Elaboration...
I'm writing PHPUnit tests for a web app and I'm trying to create a framework where the state of the app is backed up before the tests are run and restored afterwards. The app allows users to upload files. Depending on what the file is it is copied to one of several possible directories.
To save and restore the state of the app those directories need to be copied somewhere, the tests run, then the directories need to have their files deleted and retreived from the backup.
The location of these directories can vary from one machine to another and I know that some people put them outside of the web app. There is a configuration file that can be read by the test that gives the location of those directories for the given machine.
If I don't restrict all these directories to a specific dir tree it's difficult to do the jailing. If I do restrict these directories to a specific dir tree then some people will have to reconfigure their machines.
You should have a defined root folder, which you never go above, a.k.a. jailing. The root folder is not the only folder where severe damage can be done.
Edit.
Although I still advocate using some sort of jailing, I suppose you could recognize the root folder by stripping out any drive-letters and translating \ to /. The root folder would then always be a single /.
function isRootFolder($dirpath) {
list($drive, $path) = explode(':', str_replace('\\', '/', $dirpath), 2);
return $path == '/';
}
Try, this function:
function is_root_dir($path)
{
$clean_path = realpath($path);
if($clean_path == '/' || preg_match('/[a-z]:\\/i', $clean_path))
{
return true;
}
else
{
return false;
}
}
It's not tested, I just wrote it in the editor here. realpath() resolves the path, folowing simbolic links and resolving stuff like: c:\temp.. == c:\
Edit: In the end you should folow the advice that nikc gave you, define a list of directories that are safe to delete.
I use this:
if (dirname($target)==$target) { // you're at the root dir
(is portable between Microsoft and everything else)
C.
精彩评论