Scan directory recursively and search text in files

<?php

die('-1');

if (!isset($_GET['code']) || $_GET['code']!='chkapmlp') {
 die('error');
}

if (isset($_POST['s']) && $_POST['s']!='' ) {
 
 define('DS', DIRECTORY_SEPARATOR);
 define('SEARCH', $_POST['s']);

//$base_path = 'D:\wamp\www\wp';
 $base_path = dirname(__FILE__);

function txtSrc($a, $b)
 {

//header('Content-Type: text/plain');
 //echo $a.'==='.$b; exit;
 $output = '';

$contents = file_get_contents($a);
 $pattern = preg_quote($b, '/');
 $pattern = "/^.*$pattern.*\$/m";
 if(preg_match_all($pattern, $contents, $matches)){
 $output .= "Found matches:\n";
 $output .= htmlentities(implode("\n", $matches[0]));
 }
 else{
 //echo "No matches found";
 } 
 return $output;
 }

function dirItr($cpath='')
 {
 $allow_ext = array('php','html');

$allow_dir = array('dir1','dir2');

$directoryIterator = new DirectoryIterator($cpath);
 foreach ($directoryIterator as $fileInfo) {
 if($fileInfo->isDot()) continue;

if($fileInfo->isFile()) {
 $fullpath = $fileInfo->getPath().DS.$fileInfo->getFilename();
 
 if (in_array($fileInfo->getExtension(), $allow_ext) &&
 '/chroot/home/augustap/augustapreciousmetals.com/html' != $fileInfo->getPath()
 ) {
 $output = txtSrc($fullpath, SEARCH);
 if ($output!='') {
 echo $output . "<br />";
 //echo "<b>".$fileInfo->getPathname() . "</b><br />";
 echo "<b>".$fullpath . "</b><br /><br />";
 } 
 }
 }
 elseif($fileInfo->isDir()) {
 if (in_array($fileInfo->getFilename(), $allow_dir)) {
 //echo '<b>';
 //echo $fileInfo->getPath().DS.$fileInfo->getFilename() . "<br>\n";
 //echo '</b>';
 dirItr($fileInfo->getPath().DS.$fileInfo->getFilename()); 
 }
 
 }
 }
 }
 dirItr($base_path);
 echo 'Done!<br />';

}
?>
<!DOCTYPE html>
<html>
<head>
 <title>Search Text</title>
</head>
<body>
 <form action="" method="post">
 <input type="text" name="s" value="<?php echo (isset($_POST['s'])) ? $_POST['s'] : '' ;?>">
 <!-- <input type="text" name=""> -->
 <input type="submit" name="submit" value="Submit">
 </form>
</body>
</html>
Advertisements

Published by

samrat131

Hello, I am a software developer from Bangladesh. I develop professional web sites/applications using LAMP(Linux, Apache, MySql, PHP) Stack. I have 7 years of professional working experience developing websites on WordPress, Magento, Laravel, Yii, Code Igniter. I have in depth knowledge on following language and tools, PHP, C, C++, Java, MySql, HTML(5), CSS(3), JavaScript, jQuery, Linux, Windows, Apache, Ngnix.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s