Deleting Directories Containing Files
Removing a directory is easy, but what happens when the directory contains files? The rmdir() function fails if there are any files in the directory. To delete the directory, you must first delete all the files it contains.
There are several ways to do this. One option is to use a recursive function that deletes all files and folders in the directory, including any nested directories. Here's an example:
function deleteDir(string $dirPath): void { if (! is_dir($dirPath)) { throw new InvalidArgumentException("$dirPath must be a directory"); } if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') { $dirPath .= '/'; } $files = glob($dirPath . '*', GLOB_MARK); foreach ($files as $file) { if (is_dir($file)) { deleteDir($file); } else { unlink($file); } } rmdir($dirPath); }
Alternatively, if you're using PHP 5.2 or later, you can use a RecursiveIterator to delete the directory without implementing the recursion yourself:
function removeDir(string $dir): void { $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) { if ($file->isDir()){ rmdir($file->getPathname()); } else { unlink($file->getPathname()); } } rmdir($dir); }
The above is the detailed content of How to Delete a Directory Containing Files in PHP?. For more information, please follow other related articles on the PHP Chinese website!