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

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

黄舟
Release: 2023-03-06 13:44:01
Original
1260 people have browsed it

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);  
    }  
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template