Avatar of Neil Thompson
Neil Thompson
Flag for United Kingdom of Great Britain and Northern Ireland asked on

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

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
PHP

Avatar of undefined
Last Comment
Chris Stanyon

8/22/2022 - Mon
David Favor

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 Thompson

ASKER
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

ASKER CERTIFIED SOLUTION
Chris Stanyon

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck