Skip to content

Instantly share code, notes, and snippets.

@GuilhermeRossato
Last active March 27, 2018 15:33
Show Gist options
  • Save GuilhermeRossato/34c99c5887c5950c434d3258034df5c2 to your computer and use it in GitHub Desktop.
Save GuilhermeRossato/34c99c5887c5950c434d3258034df5c2 to your computer and use it in GitHub Desktop.
Search files recursively for a given extension in PHP
<?php
function search_recursively_for_extension($directory, &$array, $extension=".dat") {
//global $debug;
if (substr($directory, -1) === "/" || substr($directory, -1) === "\\") {
$directory = substr($directory, strlen($directory)-1);
}
$nodes = scandir($directory);
//$debug .= ("Reading Directory: ".$directory."\n").(($nodes === false || $nodes === NULL)?("false, ".(file_exists($directory)?"it does exist":"it doesn't even exist")."\n"):(var_export($nodes, true)."\n"));
if (is_array($nodes)) {
foreach ($nodes as $node) {
if ($node === "." || $node === "..") continue;
$node = $directory.DIRECTORY_SEPARATOR.$node;
if (is_dir($node)) {
search_recursively_for_extension($node, $array, $extension);
} else if (substr($node, -strlen($extension)) === $extension) {
$array[] = $node;
}
}
}
}
/*
* // Usage:
* $arr = [];
* search_recursively_for_extension(__DIR__, $arr, ".php");
* foreach ($arr as $fileName)
* echo $fileName."<br>\n";
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment