12

I am looking for the fastest approach for searching for some string into some folder structure. I know that I can get all content from the file with file_get_contents, but I am not sure if is fast. Maybe there is already some solution that works fast. I was thinking about using scandir to get all files and file_get_contents to read it's content and strpos to check if the string exist.

Do you think there is some better way od doing this?

Or maybe trying to use php exec with grep?

Thanks in advance!

Bob
  • 8,392
  • 12
  • 55
  • 96

2 Answers2

19

Your two options are DirectoryIterator or glob:

$string = 'something';

$dir = new DirectoryIterator('some_dir');
foreach ($dir as $file) {
    $content = file_get_contents($file->getPathname());
    if (strpos($content, $string) !== false) {
        // Bingo
    }
}

$dir = 'some_dir';
foreach (glob("$dir/*") as $file) {
    $content = file_get_contents("$dir/$file");
    if (strpos($content, $string) !== false) {
        // Bingo
    }
}

In terms of performance, you can always compute the real-time speed of your code or find out memory usage quite easily. For larger files, you might want to use an alternative to file_get_contents.

Community
  • 1
  • 1
hohner
  • 11,498
  • 8
  • 49
  • 84
  • your solutions checks filenames and I need to check file content. is there a big difference to the code? – Bob Feb 23 '13 at 14:55
3

use directory iterator and foreach: http://php.net/manual/en/class.directoryiterator.php