Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.