Search in text files recursively with PHP - Grep

Submitted by Anonymous (not verified) on Sat, 03/21/2009 - 00:18

Every linux user knows the power of grep, which saves us hours. Sometimes we need to find a string/word from html-output of a large CMS, but we dont know in which directoty/file is it. PHP-Grep helps us in this situation with searching in all directories/files under given path.

/**
* powered by @cafewebmaster.com
* free for private use
* please support us with donations
*/

define("SLASH", stristr($_SERVER[SERVER_SOFTWARE], "win") ? "\\" : "/");

$path = ($_POST[path]) ? $_POST[path] : dirname(__FILE__) ;
$q = $_POST[q];

function php_grep($q, $path){

$fp = opendir($path);
while($f = readdir($fp)){
if( preg_match("#^\.+$#", $f) ) continue; // ignore symbolic links
$file_full_path = $path.SLASH.$f;
if(is_dir($file_full_path)) {
$ret .= php_grep($q, $file_full_path);
} else if( stristr(file_get_contents($file_full_path), $q) ) {
$ret .= "$file_full_path\n";
}
}
return $ret;
}

if($q){
$results = php_grep($q, $path);
}

echo <<

	
Path Query
$results

HRD;

?>