Check if a folder is empty

  • seularts
  • Graduate
  • Graduate
  • User avatar
  • Posts: 157
  • Loc: Romania

Post 3+ Months Ago

How can I check in php if a folder is empty or not!?
  • joebert
  • Genius
  • Genius
  • User avatar
  • Posts: 13511
  • Loc: Florida

Post 3+ Months Ago

My first thought is this.

PHP Code: [ Select ]
$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.

PHP Code: [ Select ]
$dh = opendir($directory);
for($i = 3; $i; $i--)
   $is_empty = (bool) (readdir($dh) === FALSE);
  1. $dh = opendir($directory);
  2. for($i = 3; $i; $i--)
  3. {
  4.    $is_empty = (bool) (readdir($dh) === FALSE);
  5. }
  6. 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.

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 43 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum

© 1998-2017. Ozzu® is a registered trademark of Unmelted, LLC.