Some times we need to search the contents of many files through php. Personally I wrote this piece of code when I was using eaccelerator, and used it to search the whole server for files that are not compiled.
Please mention that the class bellow, will perform a recursive search. So it will even parse subdirectories of the directory you will use.
Here is the main class:
Code:
<?php class searchFileContents{ var $dir_name = '';//The directory to search var $search_phrase = '';//The phrase to search in the file contents var $allowed_file_types = array('php','phps');//The file types that are searched var $foundFiles;//Files that contain the search phrase will be stored here var $myfiles;
function search($directory, $search_phrase){ $this->dir_name = $directory; $this->search_phrase = $search_phrase;
function GetDirContents($dir){ if (!is_dir($dir)){die ("Function GetDirContents: Problem reading : $dir!");} if ($root=@opendir($dir)){ while ($file=readdir($root)){ if($file=="." || $file==".."){continue;} if(is_dir($dir."/".$file)){ $files=array_merge($files,$this->GetDirContents($dir."/".$file)); }else{ $files[]=$dir."/".$file; } } } return $files; } } ?>
And here is an example of usage:
Code:
$search = new searchFileContents; $search->search('E:/', 'class'); var_dump($search->foundFiles);
In the above example we will search the whole E: disk for the word "class". Please mention the allowed_file_types property where you can put the file types that you want to be parsed. In our example we search only php and phps files.
The results are stored in the foundFiles property (array). Hope you liked this snippet :)