March 28, 201016 yr I can't get the "get_file_contents" function to work for me. Probably something fairly basic but I haven't used this function before. Example code below: <?php // check IP against ban list //$banlist = array('12.34.56.789'); <-- this works when uncommented $banlist = file_get_contents('/logs/ip-log.txt'); $ip = $_SERVER['REMOTE_ADDR']; foreach($banlist as $banned) if (strpos($ip, $banned) !== false) { die('Your IP address is on our ban list.'); } ?> Writing the array directly results in a match, but calling the file as a string does not, and I can't work out why. By the way: this is intended to be used because the usual .htaccess approach is not practical in this case. I would normally opt for that.
March 28, 201016 yr Writing the array directly results in a match, but calling the file as a string does not, and I can't work out why. You've answered your own question really. file_get_contents returns the file as a string, not an array. If you want the file returned as an array, use file() instead. Or you could do as you were doing without the foreach. Or, depending how the text file is formatted, you could read it line by line with fopen, fgets and feof. PHP ref here
March 28, 201016 yr Author What's the difference? I thought that strings were the plain text contents of arrays, like array('red','blue','green').
March 28, 201016 yr Indeed they are but file_get_contents doesn't return an array, just a string, which is why you can't use foreach. How is the file formatted? one entry per line? For that, use one one of the methods above. Or you could convert a string in to an array, using explode().
March 28, 201016 yr Author Yes, it's one entry per line, but it comprises the date of entry, the IP, and the referrer, logged by PHP elsewhere. I just want to check and match the IPs from it.
March 28, 201016 yr In that case, something like : <?php $banlist = file('/logs/ip-log.txt'); $ip = $_SERVER['REMOTE_ADDR']; foreach($banlist as $banned){ if (strpos($banned, $ip) !== false) { die('Your IP address is on our ban list.'); } } ?> would probably do.
March 28, 201016 yr Yes, it's one entry per line, but it comprises the date of entry, the IP, and the referrer, logged by PHP elsewhere. I just want to check and match the IPs from it. Why not just store the ip addresses in a database or just write them directly in the array
March 28, 201016 yr Author I can't do that. The PHP that creates the log is not really editable by me because that's how it has been set up. The data that it contains is not solely for the purpose of banning. Besides, there's no DB. @ ElanMan. Thanks for your example. I'll try that.
Create an account or sign in to comment