Home >Backend Development >PHP Problem >How to delete directories recursively in php
php method to recursively delete a directory: first use the opendir function to open the directory handle; then read the entry from the directory handle, and use the readdir function to return the file name of the next file in the directory; finally delete the directory in sequence, and Just close the directory handle.
Related functions:
opendir() function opens a directory handle. If successful, the function returns a directory stream, otherwise it returns false and an error.
(Related learning video recommendations: java video tutorial)
closedir() function closes the directory handle.
readdir() function returns the file name of the next file in the directory.
Code sample:
<?php //递归删除目录 $path = "D:/a"; //调用递归函数 $res = diGUiRmDir($path); //输出结果 var_dump($res); function diGUiRmDir($path){ //打开目录句柄 $handle = opendir($path); //readdir() 从目录句柄中读取条目 //返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回 while(false !== $filename = readdir($handle)){ if ($filename =='.' || $filename =='..') { //跳过 . ..文件夹 continue; } //判断是否为目录 if (is_dir($path.'/'.$filename)) { $current_func = __FUNCTION__; //是目录,递归删除 $current_func = ($path.'/'.$filename); }else{ //是文件,删除 unlink($path.'/'.$filename); //unlink() 删除文件 返回bool } } //目录删除完毕 closedir($handle); //关闭目录句柄 return rmdir($path); // 删除目录返回结果 }
Related recommendations:php training
The above is the detailed content of How to delete directories recursively in php. For more information, please follow other related articles on the PHP Chinese website!