pantinosm Posted May 23, 2011 Share Posted May 23, 2011 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); ?> Quote Link to comment https://forums.phpfreaks.com/topic/237184-read-a-line-from-a-file-and-compare-it/ Share on other sites More sharing options...
Fadion Posted May 23, 2011 Share Posted May 23, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/237184-read-a-line-from-a-file-and-compare-it/#findComment-1218987 Share on other sites More sharing options...
salathe Posted May 23, 2011 Share Posted May 23, 2011 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). Quote Link to comment https://forums.phpfreaks.com/topic/237184-read-a-line-from-a-file-and-compare-it/#findComment-1218991 Share on other sites More sharing options...
AbraCadaver Posted May 23, 2011 Share Posted May 23, 2011 No need to loop either: $ip = '11.11.11.11'; $lines = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); if(in_array($ip, $lines)) { echo "FOUND"; } else { echo "NOT FOUND"; } Quote Link to comment https://forums.phpfreaks.com/topic/237184-read-a-line-from-a-file-and-compare-it/#findComment-1219120 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.