问题:
如何有效删除目录及其全部内容,包括任何子目录和关联文件,使用PHP?
答案:
为了解决这个递归目录删除任务,我们使用 rmdir 手册页中用户提供的方法:
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); } }
以上是如何在 PHP 中递归删除目录及其内容?的详细内容。更多信息请关注PHP中文网其他相关文章!