前言

今天在写一个demo的时候需要循环删除目录下文件。如下想删temp下文件和目录。

php循环遍历删除文件下文件和目录_开发语言

具体实现

private function deleteDir($dirPath)
    {
        if (is_dir($dirPath)) {
            $contents = scandir($dirPath);
            // 如果是空目录
            if (count($contents) == 2) {
                rmdir($dirPath);
                return;
            }

            // 不是空目录
            foreach ($contents as $content) {
                if ($content !== '.' && $content !== "..") {
                    $itemPath = $dirPath . '/' . $content;
                    if (is_dir($itemPath)) {
                        $this->deleteDir($itemPath);
                    }

                    if (is_file($itemPath)) {
                        unlink($itemPath);
                    }
                }
            }
        }
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.

实现效果

php循环遍历删除文件下文件和目录_开发语言_02