PHP recursive delete function

后端 未结 3 1645
误落风尘
误落风尘 2021-01-19 03:13

I wrote recursive PHP function for folder deletion. I wonder, how do I modify this function to delete all files and folders in webhosting, excluding given array of files and

相关标签:
3条回答
  • 2021-01-19 03:34
    1. You could provide an extra array parameter $exclusions to recursive_remove_directory(), but you'll have to pass this parameter every time recursively.

    2. Make $exclusions global. This way it can be accessed in every level of recursion.

    0 讨论(0)
  • 2021-01-19 03:40

    Try something like this:

    $it = new RecursiveIteratorIterator(
      new RecursiveDirectoryIterator('%yourBaseDir%'),
      RecursiveIteratorIterator::CHILD_FIRST
    );
    
    $excludeDirsNames = array();
    $excludeFileNames = array('.htaccess');
    
    foreach($it as $entry) {
      if ($entry->isDir()) {
        if (!in_array($entry->getBasename(), $excludeDirsNames)) {
          try {
            rmdir($entry->getPathname());
          }
          catch (Exception $ex) {
            // dir not empty
          }
        }
      }
      elseif (!in_array($entry->getFileName(), $excludeFileNames)) {
        unlink($entry->getPathname());
      }
    }
    
    0 讨论(0)
  • 2021-01-19 03:45

    I'm using this function to delete the folder with all files and subfolders:

    function removedir($dir) {
        if (substr($dir, strlen($dir) - 1, 1) != '/')
            $dir .= '/';
        if ($handle = opendir($dir)) {
            while ($obj = readdir($handle)) {
                if ($obj != '.' && $obj != '..') {
                    if (is_dir($dir . $obj)) {
                        if (!removedir($dir . $obj))
                            return false;
                    }
                    else if (is_file($dir . $obj)) {
                        if (!unlink($dir . $obj))
                            return false;
                    }
                }
            }
            closedir($handle);
            if (!@rmdir($dir))
                return false;
            return true;
        }
        return false;
    }
    
    $folder_to_delete = "folder"; // folder to be deleted
    
    echo removedir($folder_to_delete) ? 'done' : 'not done';
    

    Iirc I got this from php.net

    0 讨论(0)
提交回复
热议问题