My first thought is this.
$is_empty = (bool) (count(scandir($folder)) == 2);
If I create a folder and run that, it tells me the folder is empty. If I put a file, folder, or symlink in the folder and then run it I'm told the folder is not empty.
It does this because scandir will return dot (current folder) and dot-dot (parent folder) by themselves if the folder is empty. So if the number of entries returned from scandir is two, the folder should be empty.
--
It seems pretty inefficient to gather the entire file list of a folder to count it when we just want to know if a folder is empty though. Especially when you consider that scandir sorts that list before it returns it.
Another way would be to use opendir and readdir.
$dh = opendir($directory);
for($i = 3; $i; $i--)
{
$is_empty = (bool) (readdir($dh) === FALSE);
}
closedir($dh);
- $dh = opendir($directory);
- for($i = 3; $i; $i--)
- {
- $is_empty = (bool) (readdir($dh) === FALSE);
- }
- closedir($dh);
The thought behind this is that the first two entries returned by readdir are going to be dot and dot-dot. If we skip past them, and are given anything other than a boolean false, we immediately know the directory isn't empty. If we're given the false, we know it's empty. In either case there's no need to look any further in the directory and we can close it and move on. readdir, with the exception of dot and dot-dot always being at the beginning because they're special by default, will return things as they're found on the filesystem, it doesn't sort anything like scandir does.
Strong with this one, the sudo is.