I am trying to create a php script that will search through a directory (and all its sub-directories) on a server, and then search for a specific string in all files, only if the file is a certain type - eg: look in php or html files, but not in jpg or png files.
I have a script that will search the directory and list the files, but not one that will search for the string.
There are a few similar questions on SO that do parts of this, but I need a little help bringing it all together in one script.
I need to be able to make the script search only in certain types of files in order to limit the running resource of the script.
So the script needs to do the following:
. search the directory (and sub-directories)
. check if extension is .php or .htm or .html
. if no, move to the next file
. if yes, look inside the content of the file for "mystring"
. if the file does not contain the string, move to the next file
. if the file does contain the string, output the filename and path
The end result is to load the php file in a browser window and have it output a list of all found files, with paths:
/mypath/filename1.php
/mypath/filename2.htm
/etc
I have this script so far that will search all directories and sub-directories and look for a particular file type:
$path = "/mypath/toplevel/";
$count = 0;
$folder = "root";
function list_all_files($path) {
global $count;
$handle = opendir($path);
while ($file = readdir($handle)) {
if($file != '.' && $file != '..') {
if(is_dir($path . "/" . $file)) {
list_all_files($path . "/" . $file);
}
if(!is_dir($path . "/" . $file)) {
if ((strpos($file, '.php') !== false) || (strpos($file, '.htm') !== false) || (strpos($file, '.html') !== false)) {
$fileName = "" . $path . "/" . $file . "";
$fileContents = file_get_contents($fileName);
$searchStr = "mysearchstring";
if ($fileContents) {
$matchCount = preg_match_all($searchStr, $fileContents, $matches);
if ($matchCount) {
$count = $count + 1; echo "$fileName\n";
}
}
}
}
}
}
closedir($handle);
}
list_all_files($path);
echo "$count file(s) found.<br /><br />\n";
But this doesnt seem to work, as I am searching for a known string, but this script returns "0 files found".