Jump to content

Loop directories and print files - from a specific directory


slough

Recommended Posts

This is the folder where I keep my images:

 

/images/
/images/do-not-show-this.jpg
/images/show-the-contents-of-this-folder/
/images/show-the-contents-of-this-folder/show-me-1.jpg
/images/show-the-contents-of-this-folder/show-me-2.jpg
/images/show-the-contents-of-this-folder-too/show-me-too-1.jpg
/images/show-the-contents-of-this-folder-too/show-me-too-2.jpg
/images/show-the-contents-of-this-folder-too/but-do-not-show-this-folder/

 

I want to loop through the "images" directory and display all its sub-folders and the files they contain. I tried with this code but it will not work.

 

echo '<pre>';
if ($handle = opendir('.')) {
echo "Directory handle: $handle\n";
echo "Files:\n";

/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {

	if (is_dir($file)) {

		echo "$file\n";

		/*
			Open dir and loop its files
		*/
		if ($handle2 = opendir($file)) {

			while (false !== ($file2 = readdir($handle2))) {

				/*
					Check if it is file
				*/
				if (is_file($file2)) {
					echo "$file2\n";
				}

			}

		}
		/*
			End of open dir
		*/

	}

}

closedir($handle);
}
echo '</pre>';

 

How do I accomplish this?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.