Sometimes you just stumble over very useful code snippets and want to share them… Like with this one: Very useful piece of PHP code to scan directories, and find files within them – including files that start with a dot. The regular functions in PHP to scan directories etc. ommit those kinds of files, so this function below creates a wrapper and performs and extra search for dot-files.
/** * find files matching a pattern * using PHP "glob" function and recursion * * @return array containing all pattern-matched files * * @param string $dir - directory to start with * @param string $pattern - pattern to glob for */ function find($dir, $pattern){ // escape any character in a string that might be used to trick // a shell command into executing arbitrary commands $dir = escapeshellcmd($dir); // get a list of all matching files in the current directory $files = glob("$dir/$pattern"); // find a list of all directories in the current directory // directories beginning with a dot are also included foreach (glob("$dir/{.[^.]*,*}", GLOB_BRACE|GLOB_ONLYDIR) as $sub_dir){ $arr = find($sub_dir, $pattern); // resursive call $files = array_merge($files, $arr); // merge array with files from subdirectory } // return all found files return $files; }
There is even a version using the Unix find command instead of PHP functions:
/** * find files matching a pattern * using unix "find" command * * @return array containing all pattern-matched files * * @param string $dir - directory to start with * @param string $pattern - pattern to search */ function find($dir, $pattern){ // escape any character in a string that might be used to trick // a shell command into executing arbitrary commands $dir = escapeshellcmd($dir); // execute "find" and return string with found files $files = shell_exec("find $dir -name '$pattern' -print"); // create array from the returned string (trim will strip the last newline) $files = explode("\n", trim($files)); // return array return $files; }
No comments yet (leave a comment)