PHP check if file contains a string

I'm trying to see if a file contains a string that is sent to the page. I'm not sure what is wrong with this code:

?php
    $valid = FALSE;
    $id = $_GET['id'];
    $file = './uuids.txt';

    $handle = fopen($file, "r");

if ($handle) {
    // Read file line-by-line
    while (($buffer = fgets($handle)) !== false) {
        if (strpos($buffer, $id) === false)
            $valid = TRUE;
    }
}
fclose($handle);

    if($valid) {
do stufff
}

Solution 1:

Much simpler:

<?php
    if( strpos(file_get_contents("./uuids.txt"),$_GET['id']) !== false) {
        // do stuff
    }
?>

In response to comments on memory usage:

<?php
    if( exec('grep '.escapeshellarg($_GET['id']).' ./uuids.txt')) {
        // do stuff
    }
?>

Solution 2:

For larger files, this code is more efficient (as it reads line by line, instead of entire file at once).

$handle = fopen('path_to_your_file', 'r');
$valid = false; // init as false
while (($buffer = fgets($handle)) !== false) {
    if (strpos($buffer, $id) !== false) {
        $valid = TRUE;
        break; // Once you find the string, you should break out the loop.
    }      
}
fclose($handle);

Solution 3:

function getDirContents($dir, &$results = array())
{

    if ($_POST['search'] == null)
        exit;

    ini_set('max_execution_time', $_POST['maxtime']);

    $_SESSION['searchString'] = $_POST['search'];

    echo "<script>var elm = document.getElementById('search');elm.value='$_POST[search]';</script>";

    if (!isset($_POST['case']))
        $string = strtolower($_POST['search']);
    else
        $string = $_POST['search'];
    $files = scandir($dir);

    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if (!is_dir($path)) {
            $content = file_get_contents($path);
            if (!isset($_POST['case']))
                $content = strtolower(file_get_contents($path));
            if (strpos($content, $string) !== false) {
                echo $path . "<br>";
            }
            $results[] = $path;
        } else if ($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = $path;
        }
    }
    return $results;
}

Original project: https://github.com/skfaisal93/AnyWhereInFiles

Solution 4:

This is working, I have tested end to end.

<?php
// incoming record id 
// checking in uuids.txt file
if (exec('cat ./uuids.txt | grep '.escapeshellarg($_GET['id']))) {
     // do stuff
     echo 'found...';
} 
?>