只是想知道如何递归搜索网站文件夹目录(与上传脚本相同)并打开/读取每个文件并搜索特定字符串?
例如我可能有这个:
的search.php?字符串=你好%20world
这会运行一个过程然后输出一些像
这样的东西"hello world found inside"
httpdocs
/index.php
/contact.php
httpdocs/private/
../prviate.php
../morestuff.php
../tastey.php
httpdocs/private/love
../../goodness.php
我不希望它链接 - 抓取,因为私有文件和未链接的文件是圆的,但我希望所有其他非二进制文件都可以访问。
非常感谢欧文
答案 0 :(得分:3)
想到两个直接的解决方案。
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
。
答案 1 :(得分:1)
如果打开目录列表,您可以尝试
<?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>';
}
?>
答案 2 :(得分:0)
如果您不能使用任何上述方法,则可以使用recursive directory walk with a callback。并将您的回调定义为一个函数,该函数检查给定文件中的给定字符串。