Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Simplest way to delete a folder (including its contents)

The rmdir() function fails if the folder contains any files. I can loop through all of the the files in the directory with something like this:

foreach (scandir($dir) as $item) {     if ($item == '.' || $item == '..') continue;     unlink($dir.DIRECTORY_SEPARATOR.$item); } rmdir($dir); 

Is there any way to just delete it all at once?

like image 789
Chris B Avatar asked Aug 18 '09 21:08

Chris B


People also ask

How do I delete a folder and 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.

How can I delete all files in a directory in PHP?

If you want to delete everything from folder (including subfolders) use this combination of array_map , unlink and glob : array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );

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.


1 Answers

rrmdir() -- recursively delete directories:

function rrmdir($dir) {    foreach(glob($dir . '/*') as $file) {      if(is_dir($file)) rrmdir($file); else unlink($file);    } rmdir($dir);  } 
like image 155
Yuriy Avatar answered Sep 24 '22 23:09

Yuriy