兩個直接的解決方案浮現在腦海中。
1)使用grep
與exec
命令(僅如果服務器支持的話):
$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
中。
你可以在服務器上運行'grep'嗎? – nico 2012-07-16 16:44:53