How to create distributed/mirrored dynamic scripting website (Step - 4 Region detection and redirection)

Step four: Region detection & redirection
First of all, download the latest database

wget -O /path/IpToCountry.csv.gz

Create a table in your website database & import the data from the csv file

CREATE TABLE IF NOT EXISTS ip2country ( start int(10) unsigned NOT NULL DEFAULT '0', end int(10) unsigned NOT NULL DEFAULT '0', registry varchar(50) NOT NULL, assigned varchar(50) NOT NULL, a2 char(2) NOT NULL DEFAULT '', a3 char(3) NOT NULL DEFAULT '', country varchar(100) NOT NULL DEFAULT '', PRIMARY KEY (start,end), KEY a2 (a2) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; LOAD DATA LOCAL INFILE 'YOUR_PATH/IpToCountry.csv' INTO TABLE ip2country FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Now just need add a few line of php code at the beginning of index.php file to handle the redirect.

//If the visitor is search engine spider, then do not redirect. function check_if_spider() { $spiders = array('Googlebot', 'Yammybot', 'Openbot', 'Yahoo', 'Slurp', 'msnbot', 'ia_archiver', 'Lycos', 'Scooter', 'AltaVista', 'Teoma', 'Gigabot', 'Googlebot-Mobile'); foreach ($spiders as $spider) { if (eregi($spider, $_SERVER['HTTP_USER_AGENT'])) { return TRUE; } } return FALSE; } function checkip(){ if(check_if_spider()) return; $client_ip=ip2long($_SERVER['REMOTE_ADDR']); $rs = $db->query("select a2 from ip2c where start = $client_ip"); $row = $db->fetch_array($rs); //$row[0] will be the country code. switch($row[0]){ case 'US': //..301 Redirection header("HTTP/1.0 301 Moved Permanently"); header("Location:".$_SERVER['REQUEST_URI']); break; default: //... 301 Redirection break; } } } checkip();