Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a folder with contents using PHP [duplicate]

I need to delete a folder with contents using PHP. rmdir() and unlink() delete empty folders, but are not able to delete folders which have contents.

like image 823
Fero Avatar asked Aug 26 '09 12:08

Fero


People also ask

How do you empty a folder in PHP?

PHP rmdir() Function The rmdir() function removes an empty directory.

How do I delete a folder that is not empty?

To remove a directory that is not empty, use the rm command with the -r option for recursive deletion.

How do you remove a directory and all of its contents?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.


1 Answers

This function will allow you to delete any folder (as long as it's writable) and it's files and subdirectories.

function Delete($path) {     if (is_dir($path) === true)     {         $files = array_diff(scandir($path), array('.', '..'));          foreach ($files as $file)         {             Delete(realpath($path) . '/' . $file);         }          return rmdir($path);     }      else if (is_file($path) === true)     {         return unlink($path);     }      return false; } 

Or without recursion using RecursiveDirectoryIterator:

function Delete($path) {     if (is_dir($path) === true)     {         $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);          foreach ($files as $file)         {             if (in_array($file->getBasename(), array('.', '..')) !== true)             {                 if ($file->isDir() === true)                 {                     rmdir($file->getPathName());                 }                  else if (($file->isFile() === true) || ($file->isLink() === true))                 {                     unlink($file->getPathname());                 }             }         }          return rmdir($path);     }      else if ((is_file($path) === true) || (is_link($path) === true))     {         return unlink($path);     }      return false; } 
like image 150
Alix Axel Avatar answered Sep 19 '22 02:09

Alix Axel