PHP搜索特定文件的子目录

时间:2013-07-31 15:56:54

标签: php html

我一直在寻找解决问题的方法。我有一个网站,在许多子目录中有许多文件(都在一个主目录中)。我需要一个搜索功能,可以搜索文件名的一部分并将其返回。我需要函数不区分大小写(即如果文件名是ALL CAPS,用户搜索小写,那么它仍然应该找到文件)。我下面的函数只适用于1个目录,不能递归工作。

请帮我修改我的代码以使用多个目录。

<?php
$dirname = "./OFFICE PRECEDENTS/";//Directory to search in. *Must have a trailing slash*
$findme = $_POST["search"];

$dir = opendir($dirname);

while(false != ($file = readdir($dir))){   
    //Loop for every item in the directory.
    if(($file != ".") and ($file != "..") and ($file != ".DS_Store") and ($file != "search.php"))
    {
        //Exclude these files from the search
        $pos = stripos($file, $findme);
        if ($pos !== false){
           $thereisafile = true;//Tell the script something was found.
           //Display the search results as links.
           echo'<a href="' . $dirname . $file . '">' . $file . '</a><br>';
        }else{
            //Leave this blank
        }
    }
}

if (!isset($thereisafile)){
    echo "Nothing was found.";//Tell the user nothing was found.
    echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
?>

2 个答案:

答案 0 :(得分:3)

尝试一下:

<?php
//--- get all the directories
$dirname = '';
$findme  = "*.php";
$dirs    = glob($dirname.'*', GLOB_ONLYDIR);
$files   = array();
//--- search through each folder for the file
//--- append results to $files
foreach( $dirs as $d ) {
    $f = glob( $d .'/'. $findme );
    if( count( $f ) ) {
        $files = array_merge( $files, $f );
    }
}
if( count($files) ) {
    foreach( $files as $f ) {
        echo "<a href='{$dirname}/{$f}'>{$f}</a><br>";
    }
} else {
    echo "Nothing was found.";//Tell the user nothing was found.
    echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
?>

答案 1 :(得分:0)

@fixnode

摆脱{$dirname},它应该可以正常工作。同时修改$findme = "[Fix]*.pdf";以查找关键字而不是确切的文件名(区分大小写)。