php: Checking if a directory is empty
I found myself working with text files a little more recently and was looking for a way to tell if a directory was empty. Why? In my case I wanted to check if a directory was empty. If it wasn’t, to grab the data in those files and put them in a database.
What I didn’t want to do was have the expense of connecting to a database if the directory didn’t have any files in it to begin with. After chatting with my good friend TDavid at php-scripts.com, I decide to run with his suggestion…
Fill (or don’t fill) a variable with information if there were files in the directory. Then test the var to confirm or deny if there are files in the directory. It’s really a small bit of code…
//----- Check if ticket dir has files. If it has files,
// set a variable to hold the list of file names.
$dir = "../path/to/my/textfiles"; // set directory
if($handle = opendir($dir)){ // open directory
while(($file = readdir($handle)) !== false){
if($file != "." && $file != ".."){
$file_list[] = $file; // Set file list variable
}
}
closedir($handle); // Close directory
}
If there are files in this directory, the variable $file_list would not only exist, but also contain files. For example…
Array
(
[0] => 195972.txt
[1] => 196027.txt
[2] => 196053.txt
[3] => 196067.txt...
)
If there aren’t any files in this directory, the variable $file_list would not even exist because no $file would be inserted into it. At this point we can check/ test the variable to output or do further processing…
if(isset($file_list)){
echo "This dir has files!";
// perform further processing
// eg: collect each files contents
} else {
echo "This dir has NO files!";
// stop processing
// Not much do do with this since there are no files
}
Of course there are a few ways of checking to see if a directory is empty, but this way seemed to be the most simplistic to me. If you wanted to you could turn the entire lot into a function for reuse, and less script code clutter.
Comments? Questions?


