Home >Backend Development >PHP Tutorial >How Can I Recursively Delete a Directory and Its Contents in PHP?
Problem:
How can we effectively delete a directory and its entire contents, including any subdirectories and associated files, using PHP?
Answer:
To tackle this recursive directory deletion task, we utilize a user-contributed method from the rmdir manual page:
function rrmdir($dir) { // Verify if the specified path is a valid directory if (is_dir($dir)) { // Retrieve a list of files and subdirectories within the directory $objects = scandir($dir); // Iterate through each item in the directory foreach ($objects as $object) { // Exclude hidden files and directories (dot files) if ($object !== "." && $object !== "..") { // If the item is a directory, recursively delete it if (is_dir($dir . DIRECTORY_SEPARATOR . $object) && !is_link($dir . "/" . $object)) { rrmdir($dir . DIRECTORY_SEPARATOR . $object); } else { // Delete the item if it's a file unlink($dir . DIRECTORY_SEPARATOR . $object); } } } // Once all items within the directory have been removed, remove the directory itself rmdir($dir); } }
The above is the detailed content of How Can I Recursively Delete a Directory and Its Contents in PHP?. For more information, please follow other related articles on the PHP Chinese website!