Search code examples
phphtmlsearch-engine

How can I create a search form that searches files in a folder?


I have a search feature on my website. I would like it to search through a certain folder for files on my server and display results from there. I'd rather not use databases.

Is there a way to do this?


Solution

  • <?php
    $dir = "/your_folder_here/";
    
    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
                if($file == $_POST['SEARCHBOX_INPUT']){
                    echo('<a href="'.$dir . $file.'">'. $file .'</a>'."\n");
                }
            }
            closedir($dh);
        }
    }
    ?>
    

    From php.net mostly. Obviously change your file path. Also change the $_POST command in the middle to whatever the name of your search box input is. This will only find exact matches of your search. Some changes could be made to find close matches.