search within files in a directory
<p class="lead">During my quest to create a semi-static site that is searchable and fast to load.</p>
<p>I thought while loading all of this content in with ajax and such that it would be interesting if i could do a text search within files using just php and no databases.</p>
<p>Here is two ways to check a single file's content using a string match</p>
<pre>
if( strpos(filegetcontents("./file.txt"),$GET['id']) !== false) {
// do stuff
}
</pre>
<p>or this one which uses a cmd shell grep to find the file, which i prefer not to use but will see how performance goes. </p>
<pre>
if( exec('grep '.escapeshellarg($GET['id']).' ./file.txt')) {
// do stuff
}
</pre>
<p>so now we have to add this to a loop through each file in a directory</p>
<pre>
header('Content-Type: application/json');
$dir = "./html/";
$filetype = ".html";
$dirarray[] = "";
$searchval = "php";
// Open a directory, and read its contents
if (isdir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false) {
if (strpos($file, $filetype) !== false) {
if($file > " ") {
$filenice = $file;
$filenice = strreplace("-", " ", $filenice);
$filenice = strreplace(".html", "", $filenice);
// $file = strreplace(".html", "", $file);
if( strpos(filegetcontents($dir.$file),$searchval) !== false) {
$dirarray[$file] = $filenice;
}
}
}
}
closedir($dh);
}
}
asort($dirarray);
echo jsonencode(arrayfilter($dirarray));
</pre>
<p>this is untested code, but i think this should do it. it should add the file name to the array if the $searchval is located</p>
<h2>Sources</h2>
<p><a href='https://stackoverflow.com/questions/9059026/php-check-if-file-contains-a-string' target='_blank'>Source</a></p>
