【问题标题】:File Crawler PHP文件爬虫 PHP
【发布时间】:2012-07-16 16:42:51
【问题描述】:

只是想知道如何递归搜索网站文件夹目录(与脚本上传到的目录相同)并打开/读取每个文件并搜索特定字符串?

例如我可能有这个:

search.php?string=hello%20world

这将运行一个进程然后输出类似的东西

"hello world found inside"

httpdocs
/index.php
/contact.php

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

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

我不希望它链接-抓取,因为私有文件和未链接的文件是圆形的,但我希望其他所有非二进制文件都可以访问。

非常感谢

欧文

【问题讨论】:

  • 你能在服务器上运行grep吗?

标签: php directory web-crawler


【解决方案1】:

想到两个直接的解决方案。

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 中。

【讨论】:

    【解决方案2】:

    如果开启了目录列表,你可以试试

    <?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>';
    }
    ?>
    

    【讨论】:

      【解决方案3】:

      如果您不能使用上述任何方法,您可以使用recursive directory walk with a callback。并将您的回调定义为检查给定文件中给定字符串的函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-24
        • 2014-05-24
        • 2014-05-28
        • 2019-11-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多