foreach problems.... Banned IP list

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jkashu
Forum Commoner
Posts: 45
Joined: Tue Jan 30, 2007 12:00 pm

foreach problems.... Banned IP list

Post by jkashu »

I have a file with banned IP addresses. I want to be able to delete addresses in the list with a GET.

The file looks like this:
333.333.333.333
555.53.553.333
11.33.444.888
etc.....

The script I have tried looks like this:

Code: Select all

<?
 
$ip = $_GET['ip'];
 
$handle = fopen("ip2.php", "w");
 
foreach(file("ip.php") as $value){
 
    
    if($value != $ip){ fwrite($handle, $value); 
    
    
    }
 
}
 
fclose($handle);
 
copy("ip2.php", "ip.php");
 
?>
I am trying to write the IPs that are not equal to the GET variable to another file and then copy that file to the original at the end, however, ALL addresses are written. The if statement is always executed.

Any thoughts???

Thanks!
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: foreach problems.... Banned IP list

Post by Ambush Commander »

Use trim($value) == $ip. From what I remember, file() includes newline characters at the end.
jkashu
Forum Commoner
Posts: 45
Joined: Tue Jan 30, 2007 12:00 pm

Re: foreach problems.... Banned IP list

Post by jkashu »

Works perfectly... thanks!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: foreach problems.... Banned IP list

Post by John Cartwright »

The one liner of the day goes to... *drumrole*

Code: Select all

 
$ip = $_GET['ip']; //dont forget to validate me!
 
file_put_contents('ip.php', implode(PHP_EOL, array_diff(array_map('trim', file("ip.php")), array($ip))));
Post Reply