File Crawler PHP

青春壹個敷衍的年華 提交于 2019-12-06 08:43:15

Two immediate solutions come to mind.

1) Using grep with the exec command (only if the server supports it):

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

Once finished, every file-path that contains the query will be placed in $found. You can iterate through this array and process/display it as needed.

2) Recursively loop through the folder and open each file, search for the string, and save it if found:

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);

This should (untested) recursively search into each subfolder/file for the requested string. If it's found, it will be in the variable $found.

if directory listing is turned on you can try

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

or

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

If you cannot use any of the mentioned methods, you could use a recursive directory walk with a callback. And define your callback as a function which checks a given file for a given string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!