Forum Moderators: coopster
I didn't really know how to approach this as I'm new to reading from .txt files so I would really appreciate some help.
$newip = $_SERVER['REMOTE_ADDR'];
-CODE----------------------
$myFile = "ip.txt";
$fh = fopen($myFile, 'r');
$ip = fgets($fh);
fclose($fh);
if ($ip == $newip)
echo "denied";
else
echo "allowed";
----------------------CODE-
As you guys probably already know - this didn't work. So can I get some advice on how I could make it work, please.
Kindest Regards,
Tom.
Try the following and let me know how it works:
$myFile = "ip.txt";
$fh = fopen($myFile, 'r');
if($fh) {
[url=http://www.php.net/while]while[/url](![url=http://www.php.net/feof]feof[/url]($fh)) {
if([url=http://www.php.net/strcmp]strcmp[/url]([url=http://www.php.net/fgets]fgets[/url]($fh),$newip) == 0) {
echo 'Denied: IP already exists in file';
[url=http://www.php.net/break]break[/url];
}
}
}
fclose($fh);
Just a note: If you are already using a database for the polling system, then I'd suggest that you store the IPs in a db table as well. If the list is large enough, searching through the table will be faster than the file, and easier, too.
I tried this method and although I've deliberately duplicated the IP it has not disallowed me. I had an idea of storing each IP as a .txt file and looking for it...
Open file: 1.2.3.4.txt
If opened
Disallowed
Else
Allowed
Write file 2.3.4.5.txt
End
Would this be a little too unorthodox. It seems it.
Back on topic now. With reading lines from a file, do I have to perform my IF whilst the file is open. Can I not pull out the matching line, close the file and then do the if statement work?
You should be performing the condition while the loop, yes. You have to understand that it is going through each line of the file one at a time and checking that line against the new ip. Only at that time will you be able to tell if there is a match or not, and then you have to place accordingly.
As for it not working, I'm not sure why. You might have a few extra spaces in the text file or something so maybe giving it a trim will do the trick. You should make sure that you just have the IPs in the text file, though -- one per line.
Change this line:
if(trim(strcmp(fgets($fh)) ,$newip) == 0) {