2012-07-16 76 views
2

只是想知道如何通過遞歸搜索網站文件夾目錄(與腳本上傳到同一個目錄)並打開/讀取每個文件並搜索特定的字符串?文件抓取器PHP

例如我可能有這樣的:

的search.php字符串=你好%20world

這將運行一個進程,然後輸出somethign像

"hello world found inside" 

httpdocs 
/index.php 
/contact.php 

httpdocs/private/ 
../prviate.php 
../morestuff.php 
../tastey.php 

httpdocs/private/love 
../../goodness.php 

我不希望它鏈接 - 作爲私人文件和未鏈接的文件進行抓取,但我希望每個其他非二進制文件都能被真正訪問。

千恩萬謝

歐文

+0

你可以在服務器上運行'grep'嗎? – nico 2012-07-16 16:44:53

回答

3

兩個直接的解決方案浮現在腦海中。

1)使用grepexec命令(僅如果服務器支持的話):

$query = $_GET['string']; 
$found = array(); 
exec("grep -Ril '" . escapeshellarg($query) . "' " . $_SERVER['DOCUMENT_ROOT'], $found); 

一旦完成,包含查詢將被放置在$found每個文件路徑。你可以迭代這個數組並根據需要處理/顯示它。

2)通過文件夾遞歸循環並打開每個文件,搜索字符串,並將其保存如發現:

function search($file, $query, &$found) { 
    if (is_file($file)) { 
     $contents = file_get_contents($file); 
     if (strpos($contents, $query) !== false) { 
      // file contains the query string 
      $found[] = $file; 
     } 
    } else { 
     // file is a directory 
     $base_dir = $file; 
     $dh = opendir($base_dir); 
     while (($file = readdir($dh))) { 
      if (($file != '.') && ($file != '..')) { 
       // call search() on the found file/directory 
       search($base_dir . '/' . $file, $query, $found); 
      } 
     } 
     closedir($dh); 
    } 
} 

$query = $_GET['string']; 
$found = array(); 
search($_SERVER['DOCUMENT_ROOT'], $query, $found); 

這應該(未經測試)遞歸搜索到每個子文件夾/文件的請求字符串。如果找到它,它將在變量$found中。

0

如果目錄列表已打開,您可以嘗試

<?php 
$dir = "http://www.blah.com/"; 
foreach(scandir($dir) as $file){ 
    print '<a href="'.$dir.$file.'">'.$file.'</a><br>'; 
} 
?> 

<?php 
$dir = "http://www.blah.com/"; 
$dh = opendir($dir); 
while (false !== ($file = readdir($dh))) { 
    print '<a href="'.$dir.$file.'">'.$file.'</a><br>'; 
} 
?>