Last active
September 21, 2017 13:40
Star
You must be signed in to star a gist
Block one or more countries from accessing one or more pages on your web site
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
############################ | |
// Block one or more countries from accessing one or more pages on your web site | |
// Using Wordpress? Put this script into your functions.php | |
// Author: craig@123marbella.com | |
// Date: 21/9/2017 | |
// See: https://gist.github.com/craigedmonds/2c6bea241e5e2bd29ca64eab5a2c5a57 | |
############################ | |
//define some urls you wish to block | |
$array_of_pages_to_block = array( | |
"/my_page/", | |
"/another_page/" | |
); | |
//define a list of countries you want to block | |
//these should be two digit country codes | |
$array_of_country_codes_to_block = array( | |
"NO", | |
"ES" | |
); | |
//grab the current page the user is looking at on the site | |
$get_current_page_url = $_SERVER['REQUEST_URI']; | |
//start to prepare some output for troubleshooting purposes | |
$output_response = "Ip Address: " . $_SERVER['REMOTE_ADDR']; | |
$output_response .= "<br>"; | |
$output_response .= "Current URL: " . $get_current_page_url; | |
//check to see if this page is in the list for checking the country code | |
if(in_array($get_current_page_url, $array_of_pages_to_block)) { | |
$output_response .= "<br>"; | |
$output_response .= "This page should have the country checked as it matches one in the array."; | |
//define the page you want to redirect to | |
$redirect_page = "https://www.somepage.com/"; | |
//grab the country code from ipinfo.io (it will return for EG: NO if its norway, GB if its UK etc) | |
$country_code = file_get_contents("https://ipinfo.io/{$_SERVER['REMOTE_ADDR']}/country"); | |
//ipinfo add a whitespace to the end of the response so filter it out | |
$country_code = trim($country_code); | |
$output_response .= "<br>"; | |
$output_response .= "Country Code returned by ipinfo: " . $country_code; | |
$output_response .= "<br>"; | |
} | |
//check now to see if the country is in the block list | |
if(in_array($country_code, $array_of_country_codes_to_block)) { | |
$output_response .= "<br>"; | |
$output_response .= "Redirecting user to: " . $redirect_page; | |
//redirect the user to the $redirect_page | |
wp_redirect ($redirect_page); | |
} | |
//output troubleshooting code | |
//echo $output_response; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment