php RecursiveDirectoryIterator目录删除问题

时间:2015-04-11 19:43:29

标签: php

尝试使用目录迭代器删除空文件夹, 但总是会出现错误:删除目录后拒绝访问(代码:5)。

我在这里做错了什么?

$directory_iterator = new RecursiveDirectoryIterator($images_path, RecursiveDirectoryIterator::SKIP_DOTS);
    $objects = new RecursiveIteratorIterator($directory_iterator, RecursiveIteratorIterator::SELF_FIRST);
    try {

        echo "Removing empty folders...\n";

        foreach ($objects as $object) {

            if ($object->isDir()) {
                echo $object->getRealPath()."\n";
                $isDirEmpty = new FilesystemIterator($object->getRealPath());
                if (!$isDirEmpty->valid()){
                    echo $object->getFilename() . " - directory removed\n";
                    $path = $object->getRealPath();
                    rmdir($path);
                }
            }
        }
    } catch(Exception $e){
        echo $e->getMessage();
    }

1 个答案:

答案 0 :(得分:1)

目录迭代器仍然记得"文件夹存在,因此尝试读取其内容。但是当你删除它时,迭代器就失败了。

要修复此问题,您可以将空文件夹路径放入数组中,然后在主循环完成后将其删除。

$empty_dirs = [];
$directory_iterator = new RecursiveDirectoryIterator($images_path, RecursiveDirectoryIterator::SKIP_DOTS);
$objects = new RecursiveIteratorIterator($directory_iterator, RecursiveIteratorIterator::SELF_FIRST);
try {

    echo "Removing empty folders...\n";

    foreach ($objects as $object) {

        if ($object->isDir()) {
            echo $object->getRealPath()."\n";
            $isDirEmpty = new FilesystemIterator($object->getRealPath());
            if (!$isDirEmpty->valid()){
                echo $object->getFilename() . " - directory removed\n";
                $path = $object->getRealPath();
                //rmdir($path);
                $empty_dirs[] = $path;
            }
        }
    }
} catch(Exception $e){
    echo $e->getMessage();
}

foreach ($empty_dirs as $path)
{
    rmdir($path);
}

还有一种方法,没有数组:

$empty_dir = null;
$directory_iterator = new RecursiveDirectoryIterator($images_path, RecursiveDirectoryIterator::SKIP_DOTS);
$objects = new RecursiveIteratorIterator($directory_iterator, RecursiveIteratorIterator::SELF_FIRST);
try {

    echo "Removing empty folders...\n";

    foreach ($objects as $object) {

        if ($object->isDir()) {
            echo $object->getRealPath()."\n";
            $isDirEmpty = new FilesystemIterator($object->getRealPath());
            if (!$isDirEmpty->valid()){
                echo $object->getFilename() . " - directory removed\n";
                $path = $object->getRealPath();
                if ($empty_dir !== null)
                    rmdir($empty_dir);
                $empty_dir = $path;
            }
        }
    }
} catch(Exception $e){
    echo $e->getMessage();
}

if (!is_null($empty_dir))
    rmdir($empty_dir);