Check if folder is empty or not php

PHP Jul 03, 2020 Viewed 56 Comments 0

Because PHP's rmdir method can only delete empty folders, you need to determine whether the folder is empty. The following summarizes two ways to check if a folder is empty.

1. scandir

The scandir method always includes two elements, . and ... We can check whether the length of the files is 2.

private function isEmptyDir($dir)
    $res = scandir($dir);
    if ($res === false) {
        return false;
    return count($res) == 2;

2. FilesystemIterator

DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file.

private function isEmptyDir($dir)
    $iterator = new FilesystemIterator($dir);
    $isDirEmpty = !$iterator->valid();
    return $isDirEmpty;

Don't use glob method

Note: Glob does not see hidden file. If the file name starts with a dot, that is a hidden file, such as .htaccess. glob($dir . "/*") will return an empty array, which will cause a wrong judgment.

Updated Jul 03, 2020