限制文件夹中php脚本搜索文件的结果

时间:2019-05-05 04:46:06

标签: php

我对php没有太多经验。我有一个很好的剧本。它按文件名(例如pdf文件)搜索文件夹中的文件。它可以工作,但是我需要限制结果的数量,因为例如当我搜索pdf时,它显示了我所有的pdf文件,我对结果没有限制。我需要将其限制为仅15个结果。

另一个问题:如果什么都没找到,是否可以将消息“找不到文件”添加到结果中?


    <?php
    $dir = 'data'; 
    $exclude = array('.','..','.htaccess'); 
    $q = (isset($_GET['q']))? strtolower($_GET['q']) : ''; 
    $res = opendir($dir); 
    while(false!== ($file = readdir($res))) { 
        if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) { 
            echo "<a href='$dir/$file'>$file</a>"; 
            echo "<br>"; 
        } 
    } 
    closedir($res); 
    ?>

1 个答案:

答案 0 :(得分:1)

您可能只想在if之前或内部if语句中添加一个计数器,但是您希望这样做,这样可以解决您的问题:

反击之前是否

$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
$c = 0; // counter
while (false !== ($file = readdir($res))) {
    $c++; // add 1
    if (strpos(strtolower($file), $q) !== false && !in_array($file, $exclude)) {
        echo "<a href='$dir/$file'>$file</a>";
        echo "<br>";
    }
    if ($c > 15) {break;} // break
}
closedir($res);

Counter Inside if

$dir = 'data';
$exclude = array('.', '..', '.htaccess');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$res = opendir($dir);
$c = 0; // counter
while (false !== ($file = readdir($res))) {
    if (strpos(strtolower($file), $q) !== false && !in_array($file, $exclude)) {
        $c++; // add 1
        echo "<a href='$dir/$file'>$file</a>";
        echo "<br>";
        if ($c > 15) {break;} // break
    }
}
closedir($res);