wransik Posted March 27, 2013 Share Posted March 27, 2013 I'm trying to create a banlist based on a .txt file which has the IP's stored (one per line). Now I'm comparing the current users IP with the .txt file content like this: $file = file_get_contents( "text_file.txt" ); if( preg_match( "/$ip/", $file ) ) { // block } My problem is that non-exact matches also trigger the block, for example 127.0.0.12 is in the .txt, my IP is 127.0.0.1 and I'm getting blocked. How can I make it an exact match only ? Quote Link to comment https://forums.phpfreaks.com/topic/276232-compare-ip-with-txt-file-content/ Share on other sites More sharing options...
Solution Psycho Posted March 27, 2013 Solution Share Posted March 27, 2013 (edited) Well, your preg match is looking for anything that contains "127.0.0.1", which is contained in "127.0.0.12". You could change the regex to look for values that match the value which begin and end with a "word boundary" (line break, space, tab, etc.) if( preg_match( "#\b{$ip}\b#", $file ) Although you would be better off storing this in a database to make management easier. Edited March 27, 2013 by Psycho Quote Link to comment https://forums.phpfreaks.com/topic/276232-compare-ip-with-txt-file-content/#findComment-1421474 Share on other sites More sharing options...
litebearer Posted March 27, 2013 Share Posted March 27, 2013 Might also look into http://www.php.net/manual/en/function.file.php inconjuction with http://php.net/manual/en/function.in-array.php Quote Link to comment https://forums.phpfreaks.com/topic/276232-compare-ip-with-txt-file-content/#findComment-1421475 Share on other sites More sharing options...
wransik Posted March 27, 2013 Author Share Posted March 27, 2013 Thank you, if( preg_match( "#\b{$ip}\b#", $file ) That did the trick. Quote Link to comment https://forums.phpfreaks.com/topic/276232-compare-ip-with-txt-file-content/#findComment-1421476 Share on other sites More sharing options...
Psycho Posted March 27, 2013 Share Posted March 27, 2013 Might also look into http://www.php.net/manual/en/function.file.php inconjuction with http://php.net/manual/en/function.in-array.php I was thinking the same thing. Although RegEx is typically slower than string comparisons, in this case it's probably easier to execute a single RegEx against the entire file contents than creating ana array and looping through it. But, a database beats both of those ideas anyway. Quote Link to comment https://forums.phpfreaks.com/topic/276232-compare-ip-with-txt-file-content/#findComment-1421504 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.