2014-01-16 90 views
0

我正在嘗試搜索文件夾並檢索文件夾內的文件(獲取內容)我可以使用以下代碼搜索文件夾但我不能從那裏通過我看不到內容檢索裏面的文件。裏面的文件將是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. 
} 
?> 
+0

旁註:''&&的優先級高於'和',所以你可能要使用來代替。 –

+0

'glob()'是一個很好的選擇以及最好的命名的php函數!仍然在等待'溼()' – 2014-01-16 01:29:01

回答

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\"/>"; 
} 
+0

我有相同的結果只是找到文件夾,但我看不到它的文件 – marcos

+0

看到我更新的答案。 – 2014-01-16 02:14:00

+0

謝謝你工作正常 – marcos

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. 
} 
+0

謝謝,但我可以搜索完美的文件夾,但我是新的php,我希望能夠看到我正在搜索的文件夾裏面的文件 – marcos

+0

@marcos您只需要在空ELSE中回顯文件名你有。 – Tom

+0

@marcos對不起,誤解了你。你想要回顯你找到的1個文件(或所有文件)的內容並退出腳本? – Tom