Page 1 of 1

foreach problems.... Banned IP list

Posted: Sat Mar 08, 2008 8:16 pm
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!

Re: foreach problems.... Banned IP list

Posted: Sat Mar 08, 2008 9:12 pm
by Ambush Commander
Use trim($value) == $ip. From what I remember, file() includes newline characters at the end.

Re: foreach problems.... Banned IP list

Posted: Sat Mar 08, 2008 10:37 pm
by jkashu
Works perfectly... thanks!

Re: foreach problems.... Banned IP list

Posted: Sat Mar 08, 2008 11:15 pm
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))));