Jump to content

Compare IP with .txt file content


wransik

Recommended Posts

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 ?

Link to comment
https://forums.phpfreaks.com/topic/276232-compare-ip-with-txt-file-content/
Share on other sites

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.

 

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.