This question already has an answer here:
- Delete directory with files in it? 31 answers
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.
Try out the above code from php.net
Worked fine for me
The easiest and the best way using the system() method
You can use a cleaner method for doing a recursive delete of a directory.
Example:
Usage: