Find files with PHP

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 lines 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.

7 thoughts on “Find files with PHP

  1. Pingback: abcphp.com
  2. I am not having luck using this in windows(/php) – can you demonstrate the use – I tried to use the commands as listed on the links provided, and I only get empty arrays.

  3. @Greg – Maybe the problem appears because of backslashes in path. Backslash in path (as globe input parameter) closed within double quotes can be interpreted as escape character – and that might be the reason why you get empty array. Please see the following comment for glob() function on PHP manual. Hope this will help. Cheers!

  4. I already coded this script for dat purpose =====>

    File check by NEt Bomber

    <form name="input" action="” method=”GET”>
    Enter File NAME:
    Enter File_ PATH:

    //
    // Coded By NEt Bomber (stylized by dbunic)
    //
    // input parameters
    $fn = $_GET['fn'];
    $path = $_GET['path'];
    // list files and directories inside the specified path
    $files = scandir($path);
    // print start message 
    print 'Files in path you entred:<br>';
    // loop through each array member
    foreach ($files as $value) {
        print $value . '<br>';
        if (file_exists($path . '/' . $fn)) {
            $conf = 1;
        }
        else {
            $conf = 0;
        }
    }
    // if file was found
    if ($conf == 1) {
        print 'File exists<br>';
    }
    // file was not found
    else {
        print 'File does not exist<br>';
    }
    
  5. @NEt_Bomber – Thanks for posting your solution. PHP code is only stylized to be more readable – hope you agree. ;)

Leave a Comment