Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Find files with PHP

Wednesday, February 27th, 2013 by Servage

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;
}
Find files with PHP, 2.3 out of 5 based on 3 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.