Search Directory by PHP

Discussion in 'PHP' started by mehdi, Feb 26, 2008.

  1. #1
    i used this code to Search directory
    <?php
    if ($handle = opendir('./')) {
    while (false !== ($file = readdir($handle))) {
        $filesplit = explode(".", $file);
        $check = $filesplit[0];
    $keyword=$_GET['search'];
    if(ereg($keyword, $check))
          {
             $check .= ".$filesplit[1]";
             $valid[] = $check;
          }
    }
    for($index = 0; $index < count($valid); $index++)
    {
      echo"<br>$valid[$index]";
    }
    closedir($handle);
     
     }
    ?>
    PHP:
    but it only search the main directory, not the Subdirectories.... can someone please customize it so that Subdirectories also be searched too...
     
    mehdi, Feb 26, 2008 IP
  2. selling vcc

    selling vcc Peon

    Messages:
    361
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I read you thread, sorry I don't have the time o customize your script but I suggest that you write some recursive function that returns the results from the main directory plus the results of the function on subdirectories
    somthing like :
    
    function recursive_search($dir){
    
        //Lines of codes that search for the file
    
        //Lines of codes that returns the subdirectories
    
        //Return  $results and recursive_search($subdirectoris)
    }
    PHP:
     
    selling vcc, Feb 26, 2008 IP
  3. stoli

    stoli Peon

    Messages:
    69
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This should do the job:

    <?php
    
    $matches = Array();
    // Search /www for index.html files
    find_files('/www/', "/index.html/", $matches);
    // $matches contains matched files with full path
    print_r($matches);
    
    function find_files($path, $pattern, &$matches) {
      $path = rtrim(str_replace("\\", "/", $path), '/') . '/';
      $entries = Array();
      $dir = dir($path);
      while (false !== ($entry = $dir->read())) {
        $entries[] = $entry;
      }
      $dir->close();
      foreach ($entries as $entry) {
        $fullname = $path . $entry;
        if ($entry != '.' && $entry != '..' && is_dir($fullname)) {
          find_files($fullname, $pattern, $matches);
        } else if (is_file($fullname) && preg_match($pattern, $entry)) {
          $matches[] = $fullname;
        }
      }
    }
    
    ?>
    PHP:
    The function find_files should be passed the directory to search, the pattern to match (a regular expression) and the array to save any matched filenames in.
     
    stoli, Feb 26, 2008 IP