Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigedmonds/affb58817a2a11aa8a5bdcfedb375b73 to your computer and use it in GitHub Desktop.
Save craigedmonds/affb58817a2a11aa8a5bdcfedb375b73 to your computer and use it in GitHub Desktop.
Block one or more countries from accessing your web site
<?php
/*
Block one or more countries from accessing your web site
Written by craig@123marbella.com on 4th of October 2017
Wordpress users you can put this in the top of your functions.php file
to prevent visitors from certain countries.
*/
//create an aray of country codes you want to block
$array_of_country_codes_to_block = array(
"US",
"BR",
);
//do a lookup to ipinfo.io
//keep in mind though that ipinfo.io allows only 1,000 free lookups daily
//after that you need to use their paid api
$country_code = file_get_contents("https://ipinfo.io/{$_SERVER['REMOTE_ADDR']}/country");
$country_code = trim($country_code); //trim the response as it adds a whitespace
//check if the visitors country code matches the one retruned from ipinfo
if(in_array($country_code, $array_of_country_codes_to_block)) {
echo "Sorry, this site is not currently accessible.";
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment