Recursive Filesearch using the PHP Glob function

Jul 31, 2012

A really simple snippet of code that I tend to use when doing big imports of data into a database system. It is rare that the people preparing the files are perfect at following file naming conventions so being able to allow for a bit of flexibility is vital and this tends to do the job. Performance wise this isn’t great because you do a lot of searching that you probably shouldn’t need to do but that is up to the developer to either work around or just be aware of. At least the glob function offloads it all to the OS so performance should be fairly decent as long as you aren’t searching the whole filesystem or something silly like that. Happy globbing!

 * Util function for a recursive filesearch using glob function
if ( ! function_exists('glob_recursive')) {

// Does not support flag GLOB_BRACE
function glob_recursive($pattern, $flags = 0) {

$files = glob($pattern, $flags);

foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));

return $files;


And a link to the gist which I may keep up to date with changes… [PHP Glob Search][1].