Deleting a Directory with Nested Files
Q: I'm trying to delete a directory using rmdir() but it fails if the directory contains files. How can I delete a directory and all of its contents?
A: Here are two methods to delete a directory with all its files:
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); }
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); }
Either of these methods will effectively delete a directory including all its files and subdirectories.
The above is the detailed content of How to Delete a Directory and its Contents in PHP?. For more information, please follow other related articles on the PHP Chinese website!