getDirs() - Recursively add directory with files to an array - PHP
I needed a function that would recursively drill down into a directory, returning an array with the directory structure and files.Β I also needed the function to filter out directories and files that I didn't want listed (in addition to the parent directory markers).Β Oddly enough there wasn't much out there to provide examples of how to do this and some of the code snippet I found were just excessively big and complex, so I made getDirs():
$directories = getDirs($path); //This is the function call, the only argument is the $path of the dir. function getDirs($path){ $results = ''; //Open the path: if ($handle = opendir($path)) { //Iterate through the dir: while (false !== ($file = readdir($handle))) { //Regex to filter out files and unwanted directories (input and results) - manipulate the second preg_match() as needed: if (!preg_match("/\./", $file) && !preg_match("/^(input|results).*/i", $file)) { $dir = $path.$file."/"; $results[$file] = getDirs($dir); $results[$file]["Path"] = $dir; } //Only add files with the .php extension - you can change this to whatever extension or something like: "/\.[a-z0-9_-]$/i" to match any files. elseif(preg_match("/\.php$/i", $file)){ $results[$file] = $path.$file; } } closedir($handle); } return $results; }











