Abdulmanan Abdulmanan - 1 month ago 18
PHP Question

How to add subfolders delete functionality

This is the script it deletes all the files from a directory but it is not deleting the empty subfolders and subfolders with files in it.

<?Php
$dir='directory name here'; // directory name
$ar=scandir($dir);
$box=$_POST['box']; // Receive the file list from form

// Looping through the list of selected files ///
while (list ($key,$val) = @each ($box)) {
$path=$dir ."/".$val;
if(unlink($path)) echo "Deleted file ";
echo "$val,";
}
echo "<hr>";

/// displaying the file names with checkbox and form ////
echo "<form method=post name='f1' action=''>";
while (list ($key, $val) = each ($ar)) {
if(strlen($val)>3){
echo "<input class=roundedOne id=roundedOne type=checkbox name=box[] value='$val'>$val<br>";
}
}
echo "<input class=button1 type=submit value='Delete'></form>";
?>

Answer

This function will delete subfolders and its files:

function removeDir($dir) {
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object !== '.' && $object !== '..') {
                if (filetype($dir.'/'.$object) === "dir") {
                    removeDir($dir . '/' . $object);
                }
                else {
                    unlink($dir.'/'.$object);
                }
            }
        }
        reset($objects);
        removeDir($dir);
    }
}

You can use it by executing removeDir($dir);