0

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.

Community
  • 1
  • 1
Lukáš Jelič
  • 529
  • 3
  • 8
  • 22
  • Using the search function (like I just did) would've gotten you the answer: http://stackoverflow.com/questions/3338123/how-do-i-recursively-delete-a-directory-and-its-entire-contents-filessub-dirs – Sebastian Wramba Mar 18 '12 at 17:34
  • http://lixlpixel.org/recursive_function/php/recursive_directory_delete/ – rjz Mar 18 '12 at 17:34

3 Answers3

23

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.

amurrell
  • 2,383
  • 22
  • 26
lorenzo-s
  • 16,603
  • 15
  • 54
  • 86
  • 1
    There is a typo that made deep levels of directories not work. if (filetype($dir."/".$object) == "dir") rmdir($dir."/".$object); should be rrmdir so as to call the function again... Otherwise, awesome! – amurrell Jun 17 '14 at 20:15
3

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.

alex
  • 479,566
  • 201
  • 878
  • 984
  • if there are sub-folders with files, this functions doesnt work.. delete your post please, not to waste users time.. – T.Todua Nov 26 '14 at 09:12
  • 3
    @tazotodua Instead of writing a poorly constructed sentence stating it *doesn't work*, why don't you explain why it doesn't work so I could fix it? – alex Nov 26 '14 at 23:27
0

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.

d_inevitable
  • 4,381
  • 2
  • 29
  • 48