Jump to content

Compare IP with .txt file content


wransik
Go to solution Solved by Psycho,

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
Share on other sites

  • Solution

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 by Psycho
Link to comment
Share on other sites

 

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.