搜索文件夹并获取其中的文件内容

时间:2014-01-16 01:24:17

标签: php

我正在尝试搜索文件夹并检索文件夹内的文件(获取内容)我可以使用以下代码搜索文件夹但我无法从那里传递我看不到检索内部文件的内容。里面的文件将是txt文件,我希望能够打开然后看到。 怎么能实现我想要的?谢谢。

 <?php   
$dirname = "C:\windows";//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.
echo'<a href="' . $dirname . $file . '">' . $file . '</a><br>';
}else{

}
}
}
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 :(得分:0)

以下代码使用递归函数来搜索目录。我希望它能解决你的问题。

function scandir_r($dir){
$files = array_diff(scandir($dir), array(".", ".."));
$arr = array();
    foreach($files as $file){
    $arr[] = $dir.DIRECTORY_SEPARATOR.$file;
        if(is_dir($dir.DIRECTORY_SEPARATOR.$file)){
        $arr = array_merge($arr, scandir_r($dir.DIRECTORY_SEPARATOR.$file));
        }
    }
return($arr);
}

$dirname = "C:\windows";
$findme = "/".preg_quote($_POST["search"], "/")."/";
$files = preg_grep($findme, scandir_r($dirname));
if(sizeof($files)){
    foreach($files as $file){
    $_file = $dirname.DIRECTORY_SEPARATOR.$file;
    echo "<a href=\"$_file\">$file</a><br/>";
    }
}
else{
echo "Nothing was found.";
echo "<img src=\"yourimagehere.jpg\"/>";
}

答案 1 :(得分:0)

新代码

<?php   
$dirname = "C:\\Windows\\";//Directory to search in. *Must have a trailing slash*
$findme = 'maxlink'; //$_POST["search"];

$files = scandir($dirname);


foreach ($files AS $file)
{
    if ($file == '.' or $file == '..' or $file == '.DS_Store' or $file == 'search.php') continue;

    if (stripos($file, $findme) !== false)
    {
        $found = true;
        echo 'FOUND FILE <a href="' . $dirname . $file . '">' . $file . '</a><hr>';
        echo 'OPENING IT:<br>';
        echo file_get_contents($dirname . $file);
        echo '<hr>';
    }
    else
    {
        echo 'not found: <a href="' . $dirname . $file . '">' . $file . '</a><br>';
    }
}

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