Home  >  Article  >  Backend Development  >  How to delete empty folders in php

How to delete empty folders in php

藏色散人
藏色散人Original
2021-06-18 11:00:032004browse

How to delete empty folders in php: 1. Traverse the directory and subdirectories; 2. Use scandir to determine whether the directory is empty. If it is empty, use "rmdir" to delete the empty folder.

How to delete empty folders in php

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

How to delete empty folders with php?

php Delete empty directories and empty subdirectories

Steps:

1. Traverse directories and subdirectories

2. Use scandir to determine whether the directory is empty. If it is empty, use rmdir to delete it.

<?php
/** 删除所有空目录
* @param String $path 目录路径
*/
function rm_empty_dir($path){
    if(is_dir($path) && ($handle = opendir($path))!==false){
        while(($file=readdir($handle))!==false){     // 遍历文件夹
            if($file!=&#39;.&#39; && $file!=&#39;..&#39;){
                $curfile = $path.&#39;/&#39;.$file;          // 当前目录
                if(is_dir($curfile)){                // 目录
                    rm_empty_dir($curfile);          // 如果是目录则继续遍历
                    if(count(scandir($curfile))==2){ // 目录为空,=2是因为. 和 ..存在
                        rmdir($curfile);             // 删除空目录
                    }
                }
            }
        }
        closedir($handle);
    }
}
 
$folder = &#39;目标文件夹&#39;;
 
rm_empty_dir($folder);
?>

Using shell is much simpler:

find 目标文件夹 -mindepth 1 -depth -empty -type d -exec rm -r {} \;

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete empty folders 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