PHP check if file contains a string

WildBill picture WildBill · Jan 30, 2012 · Viewed 95.1k times · Source

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
}

Answer

Niet the Dark Absol picture Niet the Dark Absol · Jan 30, 2012

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
    }
?>