0

I have a .txt file which contains about 100.000 IP's (Blacklisted), I want to check if the current user IP is present in that .txt file, if yes script execution should stop.

What would be the most efficient way to do this without using .htaccess.

Marius Prollak
  • 368
  • 1
  • 7
  • 22

2 Answers2

1
$file = file_get_contents( "your_text_file.txt" );
if( preg_match( "/$ip/", $file ) ) {
  // block
}

If you're going to block using preg_match you may want to add the newline to the search string and escape the period characters because otherwise they will match any single character ( however unlikely, this may block normal users ). Htaccess is much better suited for this or even a database query.

Adam
  • 1,080
  • 1
  • 9
  • 17
  • This will also match on near same IP's or ? I mean, if I have 127.0.0.12 in the ban list, and my IP is 127.0.0.1 it will also block ? – Marius Prollak Mar 27 '13 at 19:05
  • If each IP address is on a new line add \n to the end of the search string for example "/127\.0\.0\.12\n/" you can use str_replace to swap out the "." characters for "\." – Adam Mar 27 '13 at 19:55
  • Thanks, in the meantime I found this: `if( preg_match( "#\b{$ip}\b#", $file )` – Marius Prollak Mar 27 '13 at 20:13
0

I think the way you are going to store the data will help you to lookup faster. Keeping the data into the sorted format and then try to do the binary search kind of thing help you to search the thing faster. I am just suggesting the theory part :)

Devesh
  • 4,500
  • 1
  • 17
  • 28