Jump to content

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).

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.