Check if a folder is empty

  • seularts
  • Graduate
  • Graduate
  • User avatar
  • Joined: Jan 02, 2007
  • Posts: 147
  • Loc: Romania
  • Status: Offline

Post April 21st, 2010, 1:20 pm

How can I check in php if a folder is empty or not!?
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post April 21st, 2010, 1:20 pm

  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13455
  • Loc: Florida
  • Status: Offline

Post April 22nd, 2010, 2:49 am

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);
}
closedir($dh);
  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.
Strong with this one, the sudo is.

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 119 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
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.