开发者

Search on files in a folder

I have a sea开发者_如何学Crch box on my site. If a student enters some text, the script must search for files with that type of name in a folder.

How to read folder and search for files?


Depending on your OS and the magnitude of files in the folder, you could go about it a few different ways. The simplest way would be to use glob():

$safer = escapeshellarg( $_REQUEST['search'] );
$results = glob( "$dir/*$safer*" );

This should give you the same results as "ls *something*" in that directory.

If you have a more specific search pattern in mind and a modest magnitude of files in the directory, scandir() will give you an array you could use preg_match() on.

If you have a vast number of files, you might consider leveraging /usr/bin/locate, or /usr/bin/find. These kinds of shell executions from php do incur system load. If you have a large number of students, or a public facing search, then you will want to pursue a different approach.


Read the glob() entry on the PHP Manual.


You could use the scandir function, it can return a sorted list which you can then search in the same way you would search an array. You would then also be able to use an implementation of the Levenshtein Distance Algorithm to provide a "Did you mean?" style response from your application.


MySql? you never connected to MySql or a db. plus the location of glob( "c:/windows/$safer" ) does not exist on a server.

if you want to search with glob, you need to use a couple ifs, elseifs and elses.

<?php
if(isset($_GET['s']) and $_GET['s'] != '') {
    $dir = 'dir/sub-dir';
    $ext = '.htm';
    $search = $_GET['s'];
    $results = glob("$dir/*$search*$ext");
    if(count($results) != 1) {
        foreach($results as $item) {
            echo "<li><a href='$item'>$item</a></li>\r\n";    
        }
    }
    if(count($results) == 1) {
        $item = $results[0];
        echo "<li color='blue'><a href='$item'>$item - only result</a></li>\r\n";
    }
    if(count($results) == 0) {
       echo "<li>no results to display</li>\r\n";   
    }
}
else {
    ?>
    <form action=''>
    <input name='s'>
    <input type='submit'>
    </form>
    <?php
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜