Building a recursive delete function (in php)
Here's the deal. I've got a "tree" or a "subtree" that I want to navigate and delete every element in. Each "node" may contain links to other nodes below it (no problem) OR may 开发者_JAVA百科contain links OUTSIDE that particular "tree"/"subtree". How can I build a function that only deletes "within" the specified tree?
This is the same recursive delete that you're used to. You just have to keep your links separated - one list for in-tree links, one for out-of-tree links. Alternately, you can have a flag that keeps track of the in-tree/out-of-tree state for each link - but you're going to have to distinguish when you make the link.
you need RecursiveIterator
You need to use realpath()
:
function DeleteTree($path)
{
if (is_dir($path) === true)
{
$path = realpath($path);
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
$file = realpath($path . '/' . $file);
// file is within tree
if (substr($file, 0, strlen($path)) == $path)
{
DeleteTree($file);
}
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
The above should do what you're looking for.
Oh... I just realized this may not be related to the filesystem... The fault is all yours! :P
精彩评论