0

I want to delete a main folder along with all the files and subfolders inside it. I have tried a code block that uses glob() to iterate over all files and then calls rmdir() to delete the main folder and unlink() to delete the files. However, the subfolders are not getting deleted. How can I modify this code to also delete the subfolders?

Example code:

foreach (glob($dir . '/*') as $file) {
    if (is_dir($file)) {
        rmdir($file);
    } else {
        unlink($file);
    }
}
rmdir($dir);
XRT-NoOne
  • 46
  • 8
  • Use a [RecursiveDirectoryIterator](https://www.php.net/manual/en/class.recursivedirectoryiterator.php) and a [RecursiveIteratorIterator](https://www.php.net/manual/en/class.recursiveiteratoriterator.php) to traverse the entire subtree and remove everything. – Sammitch Jun 16 '23 at 02:54
  • Does this answer your question? [Delete directory with files in it?](https://stackoverflow.com/questions/3349753/delete-directory-with-files-in-it) – steven7mwesigwa Jun 17 '23 at 02:15

1 Answers1

-1

Certainly! Here's a modified version of your code that uses delete_files() from CodeIgniter's File Helper to delete the main folder, its files, and subfolders:

// Load the File Helper
helper('file');

// Specify the directory path
$dir = 'path/to/main/folder';

// Delete all files and subfolders recursively
foreach (glob($dir . '/*') as $file) {
    if (is_dir($file)) {
        delete_files($file, true);
    } else {
        unlink($file);
    }
}

// Delete the main folder
rmdir($dir);

In this code, the delete_files() function is called for each subfolder encountered in the foreach loop. It deletes all the files and subfolders within each subfolder recursively.

If a file is encountered instead of a subfolder, it is deleted using unlink() as before.

Finally, after deleting all the files and subfolders, rmdir() is used to remove the main folder.

Remember to adjust the $dir variable with the actual path to the main folder you want to delete.

Dipnesh Parakhiya
  • 516
  • 1
  • 5
  • 17