代码之家  ›  专栏  ›  技术社区  ›  RKh

搜索文件夹中的文件

php
  •  2
  • RKh  · 技术社区  · 16 年前

    我的网站上有一个搜索框。如果学生输入了一些文本,脚本必须在文件夹中搜索具有该类型名称的文件。

    4 回复  |  直到 13 年前
        1
  •  6
  •   memnoch_proxy    16 年前

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

    这应该会给你与该目录中的“ls*something*”相同的结果。

    如果你有大量的文件,你可以考虑利用/usr/bin/locate或/usr/bin/find。从php执行这些shell确实会导致系统负载。如果你有大量的学生,或者是面向公众的搜索,那么你会想要采用不同的方法。

        2
  •  2
  •   Alix Axel    16 年前

    阅读 glob() entry 在PHP手册上。

        3
  •  0
  •   Richard Slater    16 年前

    你可以用 scandir 函数,它可以返回一个排序后的列表,然后您可以按照搜索数组的方式进行搜索。然后,您还可以使用 Levenshtein Distance Algorithm 从您的应用程序中提供“您的意思是什么?”风格的回复。

        4
  •  0
  •   Tanner Ottinger    15 年前

    MySql?你从未连接过MySql或数据库。加上glob的位置(“c:/windows/ “)在服务器上不存在。

    如果你想用glob搜索,你需要使用几个if、elseifs和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
    }
    ?>
    
    推荐文章