How to delete a folder with PHP?

Posted by om 9 August, 2009

To delete a file, or a folder and its contents i have compiled a recursive algorithm.
Hope this will be useful for all of you.

<?php
function rmdirr($dirname)
{
 
      // Sanity check
 
      if (!file_exists($dirname)) {
 
      return false;
 
      }
 
 
 
      // Simple delete for a file
 
      if (is_file($dirname) || is_link($dirname)) {
 
      return unlink($dirname);
 
      }       
 
      // Loop through the folder
 
      $dir = dir($dirname);
 
      while (false !== $entry = $dir->read()) {
 
      // Skip pointers
 
      if ($entry == '.' || $entry == '..') {
 
      continue;
 
      }
 
      // Recurse
      rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
 
      }
 
      // Clean up
      $dir->close();
 
      return rmdir($dirname);
 
      }
 
?>
  • Share/Bookmark
Categories : AJAX Tags :

Comments

No comments yet.


Leave a comment

(required)

(required)