Jump to content

Read a line from a file and compare it


pantinosm

Recommended Posts

Hi everyone.

Well, i need help how to check a file line by line, (each line contains 1 ip address) and compare it with a variable.

I have written some code but it doesn't work.

Please help!!

$refile='';
while(!feof($file))
  {
  
  $refile=fgets($file);
  if (strcmp($refile,"YES") == 0) echo $refile ."OK". "<br />";
  
   else
   echo $refile . "NO OK ". "<br />";
   
  }
fclose($file);
?>

 

Link to comment
https://forums.phpfreaks.com/topic/237184-read-a-line-from-a-file-and-compare-it/
Share on other sites

You can use a simple code like this one:

 

<?php
$ip = '11.11.11.11';
$lines = file('somefile.txt');

foreach ($lines as $line) {
     if ($line == $ip) {
          echo "$line OK<br />";
     } else {
          echo "$line BAD<br />";
     }
}
?>

 

file() returns an array where each element is a line of the read file. I assumed your file contains just IP Addresses and no parsing was needed.

Both of those code snippets suffer from the same problem, the variable containing any given line from the file ($refile and $line respectively) will contain the newline character(s) at the end of the IP address.  Since the string "1.2.3.4\n" is not the same as "1.2.3.4", none of the comparisons are doing the job as expected.

 

Options are plenty and varied, so take your pick.  A simple one is to manipulate the variable within the loop to remove the trailing newline character(s), rtrim() (docs) would be fine for that.  For the code using file(), you can pass various flags into the function call to change the default behaviour, a useful flag in this case is FILE_IGNORE_NEW_LINES (docs).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.