0

i m not sure on how to write a code to search for files in a folder. i have the code below to view all file from a folder call "FILES".

example of file have

abc-def.txt
ghi-jkl.txt

so i would like to have like an input where if i enter like abc so it will search for all file which have abc in it and display out. is it possible ?

$thelist = "";
if ($handle = opendir('./files/')) {
  while (false !== ($file = readdir($handle))){
    if ($file != "." && $file != ".."){
      $thelist .= $file . '<br>';
    }
  }
  closedir($handle);
}
echo $thelist;
unset($thelist);

i need help in it.

needhelp
  • 107
  • 1
  • 2
  • 5

3 Answers3

0

There is a nice function glob to search by pattern:

$pattern = filter_input(INPUT_POST, 'pattern', "*.txt", FILTER_SANITIZE_STRING);
foreach (glob($pattern) as $filename) {
    echo "$filename \n";
}
FieryCat
  • 1,875
  • 18
  • 28
0

This is my teaching example

<?php // demo/find_matching_files.php
/**
 * Put this script in the web root or other high-level directory
 *
 * Traverse this directory and all sub-directories down the tree
 * Show the matching files
 *
 * http://php.net/manual/en/class.recursivedirectoryiterator.php#85805
 */
error_reporting( E_ALL );

// USE THE OUTPUT BUFFER TO COLLECT THE LIST OF FILES
ob_start();

// USE THE REQUEST VARIABLE TO MATCH A SUBSTRING OF THE FILE NAME
$q = !empty($_GET['q']) ? $_GET['q'] : NULL;
if (empty($q)) trigger_error('Missing URL request argument "q=" for file name', E_USER_ERROR);

// CONSTRUCT THE REGEX
$rgx
= '#'         // REGEX DELIMITER
. preg_quote($q)
. '#'         // REGEX DELIMITER
. 'i'         // CASE-INSENSITIVE
;

// START IN THE CURRENT DIRECTORY
$path = realpath(getcwd());

// COLLECT THE DIRECTORY INFORMATION OBJECTS
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

// ITERATE OVER THE OBJECTS
foreach($objs as $name => $obj)
{
    if (preg_match($rgx, $name)) echo PHP_EOL . $name;
}

// IF THERE ARE MATCHES OR NO MATCHES
$out = ob_get_clean();
echo '<pre>';
if (empty($out))
{
    echo PHP_EOL . "No match found for <b>$q</b>.";
}
else
{
    echo PHP_EOL . "Matches for <b>$q</b>.";
}

// SHOW THE GIT BRANCH
$root = '.git/HEAD';
$text = @file_get_contents($root);
if ($text)
{
    $text = explode(DIRECTORY_SEPARATOR, $text);
    $text = array_slice($text, 2);
    $name = implode(DIRECTORY_SEPARATOR, $text);
    echo PHP_EOL . "On Git branch: $name" . PHP_EOL;
}
else
{
    echo PHP_EOL . "On Git branch: UNKNOWN" . PHP_EOL;
}

// SHOW THE MATCHES
echo $out;
Ray Paseur
  • 2,106
  • 2
  • 13
  • 18
-1

Use glob to find pathnames matching a pattern or a GlobIterator.

If you need that to be recursive use a RegexIterator and a RecursiveDirectoryIterator. See here

D Coder
  • 572
  • 4
  • 16