-2

I am trying to loop through a file of blocked IP address.

I seem to be unable to do this even when they should match.

Here is the code that checks.

$blocked_ips = file("/home/block_list.txt");
for ( $i = 0; $i < count($blocked_ips); $i++) {
    if ( $_SERVER["REMOTE_ADDR"] == $blocked_ips[$i] ) {
         exit;
    }
}

And here is the code I use to add the ip address to the file.

if ( $_SESSION["LogInAttempts"] >= "10" ) {
    $block_ip = $_SERVER["REMOTE_ADDR"];
    $block_ip = $block_ip . "\r\n";
    file_put_contents("/home/block_list.txt", $block_ip, FILE_APPEND);
}

And here is a list of ip addresses in the file. (example only)

169.254.51.183
192.168.0.1
192.168.10.84

I'm not to sure what I am doing wrong.

Tim Rideyourbike
  • 667
  • 1
  • 6
  • 14

2 Answers2

1

You don't need a loop at all. You can do that with in_array().

<?php
// Read in blocked ips list.
$blockedIps = file('/home/block_list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// Check if ip is blocked.
if(in_array($_SERVER['REMOTE_ADDR'], $blockedIps)) {
   exit;
}
thedom
  • 2,498
  • 20
  • 26
1

Make sure to account for whitespace when reading from files or receiving user input. trim() is your friend for such cases, though, as Jack noted in the comments, using FILE_IGNORE_NEW_LINES in file() will solve that for you. As the documentation says:

FILE_IGNORE_NEW_LINES

   Do not add newline at the end of each array element

Furthermore, you might find foreach a little more comfortable than your for loop, but that's a question of personal taste, ultimately. Here's a variant with the additional parameter in file() and with foreach:

$blocked_ips = file("/home/block_list.txt", FILE_IGNORE_NEW_LINES);
foreach($blocked_ips as $ip) {
    if ($_SERVER["REMOTE_ADDR"] == $ip) {
         exit;
    }
}

Note also that you shouldn't have quotes around that 10 in your code below, though with PHP's type juggling feature your code will work, of course. However, it's always a good idea to be as precise as possible. If for nothing else, for clarity: it will make the intention of your code easier to understand – also for you when you'll be looking at your code after a long time.

You can also append a string to REMOTE_ADDR without a problem (again, a question of personal taste). Finally, note that getting the IP address of a user is not as straightforward as simply calling $_SERVER['REMOTE_ADDR'] if we want to be very correct, but for most purposes it will suffice. Nevertheless, there's a very interesting discussion about getting the IP address of a user in PHP on StackOverflow I recommend everyone to read.

if ($_SESSION["LogInAttempts"] >= 10) {
    $block_ip = $_SERVER["REMOTE_ADDR"] . "\r\n";
    file_put_contents("/home/block_list.txt", $block_ip, FILE_APPEND);
}
Community
  • 1
  • 1
ljacqu
  • 2,132
  • 1
  • 17
  • 21