php循环遍历删除文件下文件和目录

前言

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

php循环遍历删除文件下文件和目录_第1张图片

具体实现

    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);
                    }
                }
            }
        }
    }

实现效果

php循环遍历删除文件下文件和目录_第2张图片

你可能感兴趣的:(随笔,php,开发语言)