-1

I am trying to use php to check if a directory is empty or not. I have seen a lot of similar questions but I have not been able to solve the problem. Namely, the following code always gives me the result that the directory is not empty:

<?php
function is_dir_empty($dir) {
    if (!is_readable($dir)) return NULL;
    $files = array_diff(scandir($dir), array('.', '..'));
    return empty($files);
}

$dir = 'images/tmp';
if (is_dir_empty($dir)) {
    echo "The folder is empty";
} else {
    echo "The folder is NOT empty";
}
?>

the directory permissions are 755 and the path is correct. I also tried with this function but the result is the same:

function is_dir_empty($dir) {
    if (!is_readable($dir)) return NULL;
    $files = glob("$dir/*");
    return empty($files);
}

5
  • 1
    What did is_readable and scandir return? Commented Jul 20, 2023 at 15:14
  • @shingo how can i check it? Commented Jul 20, 2023 at 15:28
  • Can you please explain the use case? Depending on what you want to do with this result, maybe there are other solutions. For example one odd solution would be to use rmdir, it will remove the directory and return true if the directory is empty, otherwise don't do anything and return false. Commented Jul 20, 2023 at 15:33
  • I tried your function and it works just fine. Try dump is_dir or is_readable to see if your directory really exists. It may take the root directory somewhere else then you think. Commented Jul 20, 2023 at 16:17
  • Did you check for hidden files? Commented Jul 20, 2023 at 16:20

1 Answer 1

2

Do a scandir and count the contents. An empty directory always contains . and ... So if the count is greater than 2 it is not empty.

function isDirectoryEmpty(string $dir): bool
{
    return is_dir($dir) && count(scandir($dir)) <= 2;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.