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?
Well, there's always
system('/bin/rm -rf ' . escapeshellarg($dir));
where available.
rrmdir()
-- recursively delete directories:
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
} rmdir($dir);
}
function delete_files($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
delete_files($dir."/".$object);
else unlink ($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
As per this source;
Save some time, if you want to clean a directory or delete it and you're on windows.
Use This:
chdir ($file_system_path);
exec ("del *.* /s /q");
You can use other DEL syntax, or any other shell util.
You may have to allow the service to interact with the desktop, as that's my current setting and I'm not changing it to test this.
Else you could find an alternative method here.
Try this :
exec('rm -rf '.$user_dir);
This fuction delete the directory and all subdirectories and files:
function DelDir($target) {
if(is_dir($target)) {
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
DelDir( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
}
One safe and good function located in php comments by lprent
It prevents accidentally deleting contents of symbolic links directories located in current directory
public static function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file") && !is_link($dir)) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}