Remove all files, folders and their subfolders with php
directory, file-io, php, subdirectory
Solution
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
rrmdir($dir."/".$object);
else unlink ($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>
Try out the above code from a comment on php.net
Worked fine for me
Problem
I need a script which can remove a whole directory with all their subfolders, files and etc. I tried with this function which I found in internet before few months ago but it not work completely. ``` function deleteFile($dir) { if(substr($dir, strlen($dir)-1, 1) != '/') { $dir .= '/'; } if($handle = opendir($dir)) { while($obj = readdir($handle)) { if($obj != '.' && $obj != '..') { if(is_dir($dir.$obj)) { if(!deleteFile($dir.$obj)) { echo $dir.$obj."<br />"; return false; } } elseif(is_file($dir.$obj)) { if(!unlink($dir.$obj)) { echo $dir.$obj."<br />"; return false; } } } } closedir($handle); if(!@rmdir($dir)) { echo $dir.'<br />'; return false; } return true; } return true; } ``` For the test I use a unpacked archive of prestashop and I try to delete the folder where archive is unpacked but it doesn't work. ``` /home/***/public_html/prestashop/img/p/3/ /home/***/public_html/prestashop/img/p/3 /home/***/public_html/prestashop/img/p /home/***/public_html/prestashop/img ``` These are the problem folders. At the first time I think - "May is a problem with the chmod of the files" but when I test with all files chmod permission 755 (after that with 777) - the result was the same.