Home > Article > Backend Development > How to delete directories and files recursively in php
php method to recursively delete directories and files: first call the recursive function and open the directory handle; then read the entry from the directory handle to determine whether it is a directory; finally determine if it is a directory, then delete it recursively, and determine if it is The file can be deleted.
php method to recursively delete directories and files:
<?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 free learning recommendations: phpprogramming(video)
The above is the detailed content of How to delete directories and files recursively in php. For more information, please follow other related articles on the PHP Chinese website!