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

How to delete directories recursively in php

王林
王林Original
2020-11-05 11:35:082455browse

php method to recursively delete a directory: first use the opendir function to open the directory handle; then read the entry from the directory handle, and use the readdir function to return the file name of the next file in the directory; finally delete the directory in sequence, and Just close the directory handle.

How to delete directories recursively in php

Related functions:

opendir() function opens a directory handle. If successful, the function returns a directory stream, otherwise it returns false and an error.

(Related learning video recommendations: java video tutorial)

closedir() function closes the directory handle.

readdir() function returns the file name of the next file in the directory.

Code sample:

<?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); // 删除目录返回结果
    }

Related recommendations:php training

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!

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