Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP blocking website access by country

Tags:

php

web

blocking

I want to block some countries accessing my website due to over malicious hits everyday. I have found a script here http://azuliadesigns.com/blocking-website-access-country-php/ where I can block a country from accessing the website. This seems okay for beginning. But here, I can block only one country with if($two_letter_country_code=="US").

Script

if ($_SERVER['HTTP_X_FORWARDED_FOR'])
  $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else
  $ip   = $_SERVER['REMOTE_ADDR'];

$two_letter_country_code=iptocountry($ip);

function iptocountry($ip)
{
  $numbers = explode( ".", $ip);    

  include("ip_files/".$numbers[0].".php");
  $code=($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);    

  foreach($ranges as $key => $value)
  {
    if($key<=$code)
    {
      if($ranges[$key][0]>=$code)
      {
        $country=$ranges[$key][1];break;
      }
    }
  }

  if ($country=="")
  {
    $country="unknown";
  }

  return $country;
}
if ($two_letter_country_code=="US")
  die();

My question is, what if I want to block access to multiple countries here from the database? Suppose, I have saved some country codes in my database to block them say US,IN,PK.... and so on, and I want to block access to all those. In that case, how can I modify this script to work?

What I think should work:

$country_codes_to_block = $row['block_countries']; // Fetched from database. This will give me the country codes US,IN,PK... etc.

Now modifying this line

if ($two_letter_country_code=="US")

to

if (in_array($two_letter_country_code, $country_codes_to_block))

Will this be blocking access to all the countries whose codes are given stored in database? Or should I do something else? And is this script really useful or are there any flaws I need to overcome? I am confused with these questions. Please help me...


1 Answers

In my expirience, it should work out by using in_array()

how about using common methode like if ($two_letter_country_code=="US" || $two_letter_country_code=="UK" ) is it working?

like image 174
Hasby Fahrudin Avatar answered May 07 '26 17:05

Hasby Fahrudin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!