note 102999 deleted from function.glob by danbrown
| From: | danbrown@php.net | Date: | Sat, 19 Mar 2011 15:24:07 +0000 |
| Subject: | note 102999 deleted from function.glob by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178010@lists.php.net to get a copy of this message | ||
Note Submitter: wade at NOSPAM dot kingcopeland dot com
----
I thought the safe_glob() function by âBigueNique at yahoo dot caâ was really cool so I
incorporated it into a recursive function that will search an entire subdirectory tree. The
original function is from http://www.redips.net/php/find-files-with-php/
. Below is the changed version that uses the safe_glob() function.
<?php
/**
* 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_php($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 = safe_glob("$dir/$pattern", $flags = GLOB_PATH);
// find a list of all directories in the current directory
// directories beginning with a dot are also included
foreach (array_merge(safe_glob("$dir/.[^.]*",
GLOB_PATH|GLOB_ONLYDIR|GLOB_NODOTS),
safe_glob("$dir/*",
GLOB_PATH|GLOB_ONLYDIR|GLOB_NODOTS)) as $sub_dir){
$arr = find_php($sub_dir, $pattern); // resursive call
$files = array_merge($files, $arr); // merge array with files from subdirectory
}
// return all found files
return $files;
}
?>
Using this function might look something like this:
$file_location = find_php($_SERVER
["DOCUMENT_ROOT"] . "/exaple_directory",
$pattern="example_file.jpg");
echo "The file you are looking for is at $file_location[0]";