Print folder contents recursive with indent – PHP

Today I’m doing some documentation and I want a tree where are all the files from a folder for later copy paste it and modify it.

I was close to do it by hand but…come on! is not lot of work? is not work of developers to automatize actions that we do to often?

That’s why I just did a simple function to read a folder and display all his content even from the folders inside.

Also I there’s an incremental indent (I want it with tabs but this was much easier).

Here you have the code:

function printFiles($path,$level)
{
	if (is_dir($path)) { 
		if ($dh = opendir($path)) { 
			$spaces = str_repeat( ' ',($level*10));//spaces indent
			while (($file = readdir($dh)) !== false) { 
				$Filename=$path.$file;
				$pos=strpos($file, ".");
				if ($pos!=0||$pos===false){//no hidden files
					if (is_dir($Filename)){//directory
						echo $spaces."<b>". $file."</b><br/>";
						printFiles($Filename."/",$level+1);//recursive!
					}
					else echo $spaces.$file."<br/>";//normal files
				}
			}
			closedir($dh);
		}
	}
}
 
printFiles($_SERVER["DOCUMENT_ROOT"]."/",0);//start!
Related Posts Related Websites
Help sharing and Flatter me ;)

Share

Leave a Reply

Follow me