Recursively list directories in php

For a project I needed all directories listed from a given root directory. After searching around the net and finding a lot of old posts handling that with scandir(), is_dir() and stuff, I decided to write my own recursive implementation. I went quite well but after some time (it was quite late I must confess) my head started to “spin me right round, baby, right round like a record baby, right round round round”.😉 But luckily for me, google was very nice at the end because all I needed was some SPL magic (and PHP 5.3 of course):

static public function listAllDirectories() {
	$dirs = new RecursiveIteratorIterator(
	        new RecursiveDirectoryIterator(ROOTDIR),
            RecursiveIteratorIterator::CHILD_FIRST);
	foreach ($dirs as $value) {
		if ($value->isDir()) {
			$result[] = substr($value, strlen(ROOTDIR) + 1);
		}
	}
	sort($result);
	return $result;
}

All we do is recursively iterate (with a RecursiveIteratorIterator()) through a RecursiveDirectoryIterator. Because also files are listed this way I had to check for directories with isDir() and save all occurences, stripped from the given root directory and the last apending ‘/’. That’s all folks, the final list looks like this: foo, foo/bar, foo/bar/1, bar, bar/foo, …

References

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: