Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if file contains a string

Tags:

php

fopen

strpos

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 } 
like image 292
WildBill Avatar asked Jan 30 '12 03:01

WildBill


2 Answers

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     } ?> 
like image 168
Niet the Dark Absol Avatar answered Sep 18 '22 23:09

Niet the Dark Absol


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); 
like image 35
xdazz Avatar answered Sep 21 '22 23:09

xdazz