Home > Article > Backend Development > PHP Development Tips (5) - Code Case for Recursive Deletion of Folders
In many cases, during our development process, we need to directly operate files on the disk, which is inevitable in programming. The following code introduces how to recursively delete files on the disk:
<?php /** * ======================================= * Created by Zhihua_W. * Author: Zhihua_W * Date: 2016/12/3 0005 * Time: 下午 5:21 * Project: PHP开发小技巧 * Power: 实现递归删除文件夹 * ======================================= */ /** * 递归删除文件夹 * @param $dir 文件夹路径 * @param string $file_type */ function delFile($dir, $file_type = '') { if (is_dir($dir)) { $files = scandir($dir); //打开目录 //列出目录中的所有文件并去掉 . 和 .. foreach ($files as $filename) { if ($filename != '.' && $filename != '..') { if (!is_dir($dir . '/' . $filename)) { if (empty($file_type)) { unlink($dir . '/' . $filename); } else { if (is_array($file_type)) { //正则匹配指定文件 if (preg_match($file_type[0], $filename)) { unlink($dir . '/' . $filename); } } else { //指定包含某些字符串的文件 if (false != stristr($filename, $file_type)) { unlink($dir . '/' . $filename); } } } } else { delFile($dir . '/' . $filename); rmdir($dir . '/' . $filename); } } } } else { if (file_exists($dir)) unlink($dir); } }
You only need to pass in the path of the file to delete all files under the file. You can try it yourself......
The above is the detailed content of PHP Development Tips (5) - Code Case for Recursive Deletion of Folders. For more information, please follow other related articles on the PHP Chinese website!