0

I have an internal website that provides download links to various documents for training purposes. At this point its by department so one just navigates to the department and using php it creates links to the files in a directory.

I am trying to add a search function that will go through a directory(and subs) and find files with files names that contain a specified string.

I have tried many solutions to people asking the same question(they are everywhere, yes I have seen and tried them) on stackoverflow and cant seem to get it to work. :(

Specifically, I have found a particular example, posted here (not the accepted one) PHP scandir recursively

<?php
 function rsearch($folder, $pattern) {
 $dir = new RecursiveDirectoryIterator($folder);
 $ite = new RecursiveIteratorIterator($dir);
 $files = new RegexIterator($ite, $pattern, RegexIterator::MATCH);


 foreach($files as $file) {
     yield $file->getPathName();
}}

That I think should work, but I don't understand how to access the results.( I think I am calling correctly)

Can someone please demonstrate how to use this? I would greatly appreciate showing how to call and then access the result. For example if I wanted to find all files in $folder(and sub folders) that contain the string "apple" in the file name and list the path/name for matching files.

Thanks alot!

hderic
  • 3
  • 3

1 Answers1

0

Figured it out! (with much help from the internet), And liberal use of copy paste.

This will look at all files in a directory and sub directories and create html links to any files whose name contains the search string.

    <?php
        // input from search feild in index.html
        $search = $_POST['search'];
        // directory where files to be searched are located
        $path = './files_to_serve';
        // convert search string to lower case, file names will be lower cased a few lines down
        // that way search results are case-insensitive
        $search = strtolower($search);

        // iterate through all the files
        $iterator = new RecursiveDirectoryIterator($path);   
        foreach(new RecursiveIteratorIterator($iterator) as $file) {
            // if its not a directory and the search criteria is in the filename(lowercase)
            if ($file->isFile() && str_contains(strtolower($file->getFilename()), $search)) {
                // change all the spaces etc into a string that will work in a link
                $href = rawurlencode($file->getPathName());
                // print out the links to the files
                echo "<a href={$href}>{$file->getFileName()}</a><br>";
            }
        }
    ?>
hderic
  • 3
  • 3