Restrict country users browsing your webpage
Base of this post is on article Match users to their geo-location with PHP and PEAR Net:Geo . And base of that article is made on GeoIP Country database which is available for download as binary format and CSV format. Going through maxmind pages I figured out that it is possible to lookup IP address and country using database also! Step by step processes made it easy to export list of IP range for countries, defined in CSV file, into mysql database. Once you are done with these steps, put these PHP snippets:
- config.php
// let's put these in config.php, what do you think ?
define('ENABLE_COUNTRY_RESTRICTION', TRUE );
// list of country codes.
$GLOBALS['LIST_ALLOWED_COUNTRY_CODE']=array( 'BD', 'US', 'AU' );
- index.php
/**
* This is our content page. It will inherit CONSTANTS from config.php and check IP based country restriction.
* Variables $remote and $db are assumed to be defined and initiated according to http://vincent.delau.net/php/geoip.html
* /
require(”config.php”);
//check IP access
if ( ENABLE_COUNTRY_RESTRICTION )
{
$country_code = getCCfromIP( $remote, $db );
$country_name = getCOUNTRYfromIP( $remote, $db );
if ( !in_array( $country_code, $GLOBALS['LIST_ALLOWED_COUNTRY_CODE'] ) )
{
echo “<h1>IP restriction: <b>{ $remote}</b> from <b>{$country_name}</b></h1>”;
die( “put error message” );
}
}
// we are here now! yahooooo!!
// Our country has freedom to access rest of the contents of this page
// put your restricted/classified contents here
However, I was not satisfied with
$remote = $_SERVER['REMOTE_ADDR']; for detecting client IP. I wanted to overcome proxy issues with following code:
$remote = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
Or an extended function,
function GetRealIp()
{
$ip = false;
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
// proxy
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = explode(’, ‘, $_SERVER['HTTP_X_FORWARDED_FOR']);
if ($ip) {
array_unshift($ips, $ip);
$ip = false;
}
for ($i = 0; $i < count($ips); $i++) {
$ip_check = ip2long($ips[$i]);
/**
* PHP4 returns false if it’s not a valid ip, PHP5 returns -1
*/
if ($ip_check !== false && $ip_check != -1) {
$ip = $ips[$i];
break;
}
}
}
return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
Cool! Ain’t it?





