Page 1 of 1

deleting a folder thats not empty

Posted: Thu Dec 21, 2006 2:41 pm
by Obadiah
is something like this possible in php? i know i can delete an empty folder but how do i delete one that has contents?

Posted: Thu Dec 21, 2006 3:04 pm
by kingconnections
I am not 100% sure that is possible to do in one shot. You might have to read the contents of the dir and unlink each file. Then unlink the entire dir.

Posted: Thu Dec 21, 2006 3:19 pm
by Begby
You can do this with php 5 (I think 5.1+) and use SPL

Code: Select all

foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator('my/path/') ) as $file )
{
  $file->delete() ;
}
The $file->delete() is probably incorrect as this is from memory, you also have to filter out the '.' and '..', but with SPL you can delete an entire directory tree with about 4 or 5 lines of code similar to the above. A good place to start is http://www.wiki.cc/php and http://www.php.net/spl

Posted: Thu Dec 21, 2006 4:03 pm
by John Cartwright
which operating system?

with linux you can do this easily with

Code: Select all

rm -r /path/to/directory/

Posted: Thu Dec 21, 2006 4:12 pm
by Obadiah
im using winserver 2003

Posted: Thu Dec 21, 2006 4:17 pm
by Obadiah
im gonna see if this snippet will work

Code: Select all

<?php

function remove_directory($dir) {
  if ($handle = opendir("$dir")) {
   while (false !== ($item = readdir($handle))) {
     if ($item != "." && $item != "..") {
       if (is_dir("$dir/$item")) {
         remove_directory("$dir/$item");
       } else {
         unlink("$dir/$item");
         echo " removing $dir/$item<br>\n";
       }
     }
   }
   closedir($handle);
   rmdir($dir);
   echo "removing $dir<br>\n";
  }
}

remove_directory("/path/to/dir");

?>

Posted: Thu Dec 21, 2006 6:07 pm
by impulse()
I'm not sure how you delete files on Windows server but I believe the following code will identify if the directory is empty or not.

NOTE: This works on a Linux system but I'm not sure how many element will be in the $contents array if the directory is empty on a Windows server.



Code: Select all

$dirContents = opendir("directoryPath");

$i = 0;
while ($files = readdir($dirContents)) {
  $contents[$i] = $files;
  $i++;
}

if (count($contents) <= 2) {
  // This will run if the directory is empty.
}
else {
  // This will run if the there are files in the directory
}
If that doesn't work, try using

Code: Select all

print_r($contents);
while the directory IS empty to see how many elements are in the array and then change

Code: Select all

if (count($contents) <= 2) {
accordingly.

Hope that helps,