1

I want to know how to search for a string in a folder and display the line in php. I already have a snipset but it dont search in a folder but in ONE file i have tested by replacing /something/sisi.txt by /somthing/* and /something/*.txt .

The snipset:

        $searchthis = "jean";
        $matches = array();
        $handle = @fopen("./something/sisi.txt", "r");
        if ($handle)
        {
            while (!feof($handle))
            {
                $buffer = fgets($handle);
                if(strpos($buffer, $searchthis) !== FALSE)
                    $matches[] = $buffer;
            }
            fclose($handle);
        }
        print_r($matches);
Romain
  • 11
  • 3
  • The correct approach should be to find all of the filenames in the folder and put them in an array. Then use the existing code to loop through and execute for each filename. I don't think you can use wildcards with `fopen`. – leighboz Nov 06 '22 at 02:41
  • 1
    Does this answer your question? [Getting the names of all files in a directory with PHP](https://stackoverflow.com/questions/2922954/getting-the-names-of-all-files-in-a-directory-with-php) – kmoser Nov 06 '22 at 03:17

1 Answers1

0

I tested scandir using PHP version 7.4 and it gave expected results. The reason why I started the index of $i at 2 is because the first two indices refer to "." and ".." which wasn't necessary for the test.

edit: 11/7/2022 -> Additional optional Echo statements have been added to make the separation between files more clear.

The printr from the question code

More info on scandir is here: https://www.php.net/manual/en/function.scandir.php

<?php


$dir    = './something';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

//echo ("<p>Below will be the directory information...</p>");

$L = sizeof($files1); 
//print_r($files1);

$results = array();

for($i = 2; $i < $L; $i++) {
    //echo "<br>The value of i is: $i";
    //echo "<br>The value of files1 at i is:".$files1[$i];

    scanFile($files1[$i]);
}



function scanFile($filename) {

    //echo("<p>Scanning the file: $filename</p>");
    $searchthis = "jean";
    $matches = array();
    $handle = @fopen("./something/$filename", "r");
    if ($handle)
    {
        while (!feof($handle))
        {
            $buffer = fgets($handle);
            if(strpos($buffer, $searchthis) !== FALSE)
                $matches[] = $buffer;
        }
        fclose($handle);
    }

    for ($i = 0; $i < count($matches); $i++) {
        echo "$matches[$i] <br>";
    }
}

?>
overidon
  • 1
  • 2