PHP recursive file& folder delete function: 'Directory not empty' error message

StackOverflow https://stackoverflow.com/questions/7685541

  •  07-02-2021
  •  | 
  •  

سؤال

I'm trying to create function which removes all file and directories on webhosting excluding given files and folders arrays

function cleanUp($exdirs, $exfiles){
$it = new RecursiveIteratorIterator(
  new RecursiveDirectoryIterator('.'), 
  RecursiveIteratorIterator::CHILD_FIRST
);
foreach($it as $entry) {
  if ($entry->isDir() && !in_array($entry->getBasename(), $exdirs)) {
    rmdir($entry->getPathname());
  }
  else {
    if (!in_array($entry->getFileName(), $exfiles)) {
      unlink($entry->getPathname());
    }
    else {
      $exdirs[] = dirname($entry->getFileName());
    }
  }
}
}

And calling this function like this

$excludeDirsNames = array('cgi-bin');
$excludeFileNames = array('.htaccess', 'ws.zip', 'update.php');
cleanUp($excludeDirsNames , $excludeFileNames);

Now the problem is, it deletes but getting error message: Directory not empty on line rmdir($entry->getPathname()); several times. How to fix that problem?

هل كانت مفيدة؟

المحلول

You allow to exclude files and directories, but you don't test, if a directory contains other files, or directories, that were excluded before.

if (substr($oneExcludedFileOrDirectory, 0, strlen($currentDir) === $currentDir) {
  echo "Directory not empty";
}

Just a simple prefix comparison: Is "dir" is prefix of one of the excluded paths? Only works for absolute paths (and some other minor things), but it should explain, whats the matter.

نصائح أخرى

Here are two reasons why it not work:

1) In one of your child-folder are files you are excluding. There are not deleted, so it is not possible to "rm" the folder.

2) After the "unlink" and "rmdir"-Funktion call "clearstatcache();". I think this will solve your problem. The files are delete, but the information is still available in the cache.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top