Home  >  Article  >  Backend Development  >  PHP Development Tips (5) - Code Case for Recursive Deletion of Folders

PHP Development Tips (5) - Code Case for Recursive Deletion of Folders

黄舟
黄舟Original
2017-03-10 18:43:581199browse

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 = &#39;&#39;)  
{  
    if (is_dir($dir)) {  
        $files = scandir($dir);  
        //打开目录  
        //列出目录中的所有文件并去掉 . 和 ..  
        foreach ($files as $filename) {  
            if ($filename != &#39;.&#39; && $filename != &#39;..&#39;) {  
                if (!is_dir($dir . &#39;/&#39; . $filename)) {  
                    if (empty($file_type)) {  
                        unlink($dir . &#39;/&#39; . $filename);  
                    } else {  
                        if (is_array($file_type)) {  
                            //正则匹配指定文件  
                            if (preg_match($file_type[0], $filename)) {  
                                unlink($dir . &#39;/&#39; . $filename);  
                            }  
                        } else {  
                            //指定包含某些字符串的文件  
                            if (false != stristr($filename, $file_type)) {  
                                unlink($dir . &#39;/&#39; . $filename);  
                            }  
                        }  
                    }  
                } else {  
                    delFile($dir . &#39;/&#39; . $filename);  
                    rmdir($dir . &#39;/&#39; . $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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn