We help IT Professionals succeed at work.

iterate through a folder (and any subfolders) and remove any folders that have no files in them (and no subdirectories).

Neil Thompson
on
Hi, I want to be able to iterate through a folder (and any subfolders) and remove any folders that have no files in them (and no subdirectories).

Ideally before deleting I want to run initially and for the output to just list the number of files (or 0) in each folder

Thanks
Neil
Comment
Watch Question

David FavorFractional CTO
Distinguished Expert 2019

Commented:
The easy way is for PHP to call find to do this...

find . -type d -empty -delete

Open in new window


Or you can rewrite all find's logic (shudder)...

Best to use existing + working tools, when they exist.
Neil ThompsonSenior Systems Developer

Author

Commented:
Thanks but I'm assuming that needs some kind of shell / command line access?

I got this to work though:

<?php

if ($handle = opendir('files')) {

	while (false !== ($entry = readdir($handle))) {

		if ($entry != "." && $entry != "..") {
		
			if (is_dir("files/".$entry)) {
			
				$_count = count(glob("files/".$entry."/*"));

				if ($_count == 0) {
					 unlink("files/".$entry);
				}

			} 
		}
	}
	
	closedir($handle);
	
}

?>

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
The code you have there won't drop down through subfolders and subfolders. Take a look at the RecursiveDirectoryIterator:

$path = __DIR__ . "/files";

$dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);

foreach ($files as $file):
    if ($file->isDir() && empty(glob($file->getPathName() . "\*"))):
        echo "FOLDER IS EMPTY: " . $file->getPathName();
        unlink($file->getPathName());
    endif; 
endforeach;

Open in new window