Home > Backend Development > PHP Problem > How to delete directories and files recursively in php

How to delete directories and files recursively in php

coldplay.xixi
Release: 2023-03-07 06:56:02
Original
2086 people have browsed it

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.

How to delete directories and files recursively in php

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 ==&#39;.&#39; || $filename ==&#39;..&#39;) {  //跳过 . ..文件夹
                continue;
            }
            //判断是否为目录
            if (is_dir($path.&#39;/&#39;.$filename)) {
                $current_func = __FUNCTION__;
                //是目录,递归删除
                $current_func = ($path.&#39;/&#39;.$filename);
            }else{
                //是文件,删除
                unlink($path.&#39;/&#39;.$filename); //unlink() 删除文件 返回bool
            }
        }
        //目录删除完毕
        closedir($handle); //关闭目录句柄
        return rmdir($path); // 删除目录返回结果
    }
Copy after login

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!

Related labels:
php
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