January 14th, 2009
PHP Code To Check If A Directory Is Empty
While dealing with files and directories in PHP you will most likely at some point want to check if a folder/directory is empty. To do this, you need to write a script that does the check. There are two ways of doing this. The first is supported in PHP 4 and 5 only and the second will only work if you are running PHP 5 on your server. Here they are:
Method 1:
This code works with PHP 4 and PHP 5.
// Open directory and create an object
// The dir() function creates the object
$directory = dir('path_to_directory');
// Loop while the read method goes through each and
// every file
while ((FALSE !== ($item = $directory->read())) && ( ! isset($directory_not_empty)))
{
// If an item is not "." and "..", then something
// exists in the directory and it is not empty
if ($item != '.' && $item != '..')
{
$directory_not_empty = TRUE;
}
}
// Close the directory
$directory->close();
Method 2:
Although the code below is a lot neater and lighter, it will only work with PHP 5.
// Scans the path for directories and if there are more than 2
// directories i.e. "." and ".." then the directory is not empty
if ( ($files = @scandir('path_to_directory') && (count($files) > 2) )
{
$directory_not_empty = TRUE;
}
And there you have it. Two simple ways of checking if a directory is empty. Let me know if you found this useful in the comment block below.

















In Method 1, I think you mean:
if ($item != ‘.’ && $item != ‘..’)
Hey Geoff,
Thanks for the comment.
EDIT: You are correct, I have changed the code.
Method 1:
No, Geoff is right – think about it…
if the filename is not ‘.’ AND not ‘..’ then it MUST be a file or directory (i.e. not the current dir or parent dir)
$item can’t be equal to ‘.’ and ‘..’ at the same time, so ($item != ‘.’ || $item != ‘..’) will ALWAYS evaluate to TRUE!
Also you need to set
$directory_empty = TRUE;
at the beginning, otherwise $directory_empty will remain unset and therefore always == FALSE
Method 1 is a bit inefficient:
When you found 1 file or directory you can stop looping, you will loop trough the entire directory for all files in it. Won’t be a problem with a small amount, but still. I would suggest something like:
$directory_empty = true;
$directory = dir(’path_to_directory’);
while ($empty && FALSE !== ($item = $directory->read())) {
if ($item != ‘.’ && $item != ‘..’) {
$directory_empty = false;
}
}
Furthermore, you forgot to declare $directory_empty and initialize it to true, both your methods will always result in a filled directory
indentation doesn’t seem to take…
and i wrote a mistake myself: it should be
while ($directory_empty [...]
I have updated the code in the above post to a more comprehensive example.