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

Midhat
  • 45
  • 10
  • 1
    What did `is_readable` and `scandir` return? – shingo Jul 20 '23 at 15:14
  • @shingo how can i check it? – Midhat Jul 20 '23 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`](https://www.php.net/manual/en/function.rmdir.php), it will remove the directory and return `true` if the directory is empty, otherwise don't do anything and return `false`. – A.L Jul 20 '23 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. – Jimmy Found Jul 20 '23 at 16:17
  • Did you check for **hidden files**? – Your Common Sense Jul 20 '23 at 16:20

1 Answers1

1

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;
}
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35