tags:

views:

82

answers:

3

I want to traverse all sub-folders of a particular folder and check whether they have a special file in it otherwise delete the sub-folder.

Take this example (file.txt being the special file here):

  • folder_all
    • folder1
      • file.txt
    • folder2
      • file.txt
    • folder3
      • empty

Because "folder3" doesn't have the file, I'd like to delete it.
And this is what I want to do. Any ideas?

Thank you very much!

A: 

Simply iterate over all subfolders of folderall and check if the file folder_all/$subfoldername/file.txt exists. If not, delete it. That should be one loop.

API:

ZeissS
+2  A: 

updated code

You can use the RecursiveDirectoryIterator class:

<?php

$dir = '/path/';
$file = '/filetosearch.txt';
$paths = array();

$i = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

while($i->valid()) {

    if (!$it->isDot()) {

        $subpath = $it->getSubPath();

        if ($subpath != '') {
            // if inside a subdirectory
            // add the subpath in our array flagging it as false
            if (!array_key_exists($subpath, $paths) $paths[$subpath] = false;

            // check if it's our file
            if (substr_compare($i->getSubPathName(), $file, -strlen($file), strlen($file)) === 0)
                $paths[$subpath] = true;

    }

    $it->next();
}

// now check our paths array and delete all false (not containing the file)
foreach ($paths as $key => $value)
{
    if (!$value) rmdir($dir.$key);
}

?>
Anax
+1 for using SPL
Dennis Haarbrink
This is only half a solution. How will the OP know the name of the folder to delete then? Your solution uses the default `LEAVES_ONLY` for the `RecursiveIteratorIterator`, so it wont even tell you the folder names.
Gordon
@Gordon: updated, thanks.
Anax
A: 
function recursive_delete_if_exists($path,$file) {
   foreach (glob($path.'/*.*') as $name)
      if (is_dir($name))
         recursive_delete_if_exists($name,$file);
      elseif ($name==$file)
         unlink($path);
}

recursive_delete_if_exists('/folder_all','file.txt');
stillstanding