Monday, January 17, 2011

11:18 AM
1
In PHP you can find files with function glob. The glob function searches for all the pathnames matching pattern according to the rules used by the libc glob function, which is similar to the rules used by common shells. It is nice, but it works for the current directory only. If you need function to search whole directory subtree, then it can be done with few line more.


Here is first solution for PHP file search. I found PHP function on glob manual page PHP: glob - Manual. Original function works but ignores dot directories in subtree. So, I applied a little modification to include missing dot directories. Returned result are found files packed in array. It's important to mention implemented recursion and possible high memory consumption.



/**
 * 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;
}

If you use Unix (Linux) then you can try solution with "find" command. "Find" is very powerful and you can see how files can be searched in post The "find" command. Function will also return array with found files as the first version.


/**
 * 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;
}

Both versions return the same result, so you can choose between pure PHP version or version with "find" command.

1 comments: