In PHP how do I recursively remove all folders that aren't empty? [duplicate]

给你一囗甜甜゛ 提交于 2019-12-06 16:26:00

问题


Possible Duplicate:
How do I recursively delete a directory and its entire contents (files+sub dirs) in PHP?

I need to recursively delete a directory and subdirectories that aren't empty. I can't find any useful class or function to solve this problem.

In advance thanks for your answers.


回答1:


From the first comment in the official documentation.

http://php.net/manual/en/function.rmdir.php

<?php

 // When the directory is not empty:
 function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }

?>

Edited rmdir to rrmdir to correct typo from obvious intent to create recursive function.




回答2:


Something like this should do it...

function removeDir($path) {

    // Normalise $path.
    $path = rtrim($path, '/') . '/';

    // Remove all child files and directories.
    $items = glob($path . '*');

    foreach($items as $item) {
        is_dir($item) ? removeDir($item) : unlink($item);
    }

    // Remove directory.
    rmdir($path);
}

removeDir('/path/to/dir');

This deletes all child files and folders and then removes the top level folder passed to it.

It could do with some error checking such as testing the path supplied is a directory and making sure each deletion was successful.




回答3:


To recursively delete a directory use this:

function rrmdir($path) {
    return is_file($path)? @unlink($path): array_map(__NAMESPACE__ . '\rrmdir',glob($path.'/*'))==@rmdir($path);
}

Only tested on unix.



来源:https://stackoverflow.com/questions/9760526/in-php-how-do-i-recursively-remove-all-folders-that-arent-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!