php method to recursively delete a directory: first create a PHP sample file; then obtain the path of the file through the "DATA_DIR .'/compiled/';" method; then list the files and directories; and finally delete using the recursive method Directory is enough.
Recommended: "PHP Video Tutorial"
php Recursively delete directories
First of all, you need to know what recursion is, so that it will be easy to read and write recursive code later.
The recursive code listed below is to delete the file directory, and you can make slight changes to display the file. And directory
The code is as follows:
public function clear(){ $compile = DATA_DIR .'/compiled/'; //指文件所在路径 _rmdir($compile,1); } // 列出文件和目录 function _scandir($dir) { if(function_exists('scandir')) return scandir($dir); // 有些服务器禁用了scandir $dh = opendir($dir); $arr = array(); while($file = readdir($dh)) { if($file == '.' || $file == '..') continue; $arr[] = $file; } closedir($dh); return $arr; } // 递归删除目录 function _rmdir($dir, $keepdir = 0) { if(!is_dir($dir) || $dir == '/' || $dir == '../') return FALSE; // 避免意外删除整站数据 $files = _scandir($dir); foreach($files as $file) { if($file == '.' || $file == '..') continue; $filepath = $dir.'/'.$file; if(!is_dir($filepath)) { try{unlink($filepath);}catch(Exception $e){} }else{ _rmdir($filepath); } } if(!$keepdir) try{rmdir($dir);}catch(Exception $e){} return TRUE; }
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!