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);
}