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.
-
http://www.neurofuzzy.net Geoff
-
http://iarematt.com Matt
-
Andy P
-
http://hogerheijde.net Matthias Hogerheijde
-
http://hogerheijde.net Matthias Hogerheijde
-
http://iarematt.com Matt
-
http://moestaverne.com Thomas
-
http://iamNOTmatt.com Hielo
-
Wolf
-
http://www.pdvictor.com Peter Drinnan
-
ahsan