Page 1 of 1
Searching for a string in multiple files and folders
Posted: Fri Jan 13, 2006 11:30 am
by meemerz00
I am trying to make a search page of sorts, where the user can type in various things such as a name, account number, etc., and it will search a specific folder that has several subfolders of pdf files. I need it to actually search inside the file, and not just the file name. It then needs to return all files that match the criteria, and the user can click on each of them to view them. These files aren't in a database, just in a directory on my web server. I really don't even know where to start. Can anyone help me out?
Thanks!!!

Posted: Fri Jan 13, 2006 12:09 pm
by Chris Corbyn
You could try a combination of `grep' and `strings' via the shell for the PDF stuff.
Untested principle only...
Code: Select all
$dir = './';
$search = 'foo'; //Word to search for
$files = array();
$handle = opendir($dir);
while ($file = readdir($handle))
{
$command = 'strings '.$dir.$file.' | grep '.$search;
$result = `$command`;
if (!empty($result)) $files[] = $file;
}
closedir($handle);
print_r($files);
Posted: Fri Jan 13, 2006 12:22 pm
by Jenk
if memory serves:
Code: Select all
<?php
$files = explode("\r\n", shell_exec('grep -hrs ' . $searchstring . ' /starting/directory/'));
?>
That will recursively search for $searchstring in all files and sub-dirs in /starting/directory/ and suppress all messages except for matches and will return filenames.
Posted: Fri Jan 13, 2006 12:31 pm
by Chris Corbyn
Jenk wrote:if memory serves:
Code: Select all
<?php
$files = explode("\r\n", shell_exec('grep -hrs ' . $searchstring . ' /starting/directory/'));
?>
That will recursively search for $searchstring in all files and sub-dirs in /starting/directory/ and suppress all messages except for matches and will return filenames.
Hahaha... but mine looks better... OK maybe not

I cant remember if grep is binary safe or not.
Posted: Fri Jan 13, 2006 12:42 pm
by meemerz00
That returns the word "Array." That's it.
Posted: Fri Jan 13, 2006 1:07 pm
by John Cartwright
try print_r($files); instead of echo $files;
Posted: Tue Jan 17, 2006 9:24 am
by meemerz00
I'm afraid I've tried both....any other ideas?
Posted: Tue Jan 17, 2006 10:21 am
by foobar
meemerz00 wrote:I'm afraid I've tried both....any other ideas?
That's probably because you don't have command-line access on your server, or it's a windows server.
You can try the
Directory Functions to traverse each directory and file.
This will be pretty slow, so indexing might be a good idea.
Posted: Tue Jan 17, 2006 11:32 am
by meemerz00
It's a Windows Server. I guess I don't understand what you mean by traversing the directories and files. I'm really new at this, sorry!!
Posted: Tue Jan 17, 2006 12:02 pm
by Jenk
Code: Select all
print_r(explode("\n", shell_exec('find /I "test" *.*')));
Though you will have to manually go through all the directories as you can't use FIND recursively.