PHP Block Bots From China

Not only bots, but whole country, because they change IP's, you can never really tell if it's a bot, or a user. I doubt someone from China visit's my site, except from bots, so I blocked them.
With this script, you can block users from specific countries, just by adding 2 letter country code in $bans array.

Copy the code below and save it as block.php, then just include it right after your SQL connection (because it uses database). Also if you modify code to redirect via header "Location", make sure you don't output anything before.

If you have any questions write at info [a] webarto [.] com

/**
 * @author Webarto
 * @source http://webarto.com/61/php-block-bots-from-china
 * @copyright 2010
 */

//create table if it doesn't exist, you can remove this later
mysql_query('CREATE TABLE IF NOT EXISTS ip (
  id int(11) NOT NULL auto_increment,
  ip varchar(15) NOT NULL,
  `code` varchar(2) NOT NULL,
  PRIMARY KEY  (id),
  KEY ip (ip)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;');

$bans = array("CN", "IN"); //array of banned country codes, 2 letters eg US
$sql = mysql_query("SELECT * FROM ip WHERE ip = '".$_SERVER["REMOTE_ADDR"]."' LIMIT 1");
if(mysql_num_rows($sql) > 0){ //ip found in database
    $row = mysql_fetch_assoc($sql);
    if(in_array($row["code"], $bans)){ //check if country code is in ban array
        die("Sorry, but fsck it."); //or do whatever you want
    }
}else{ //ip not found in database, find out where IP is from
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/php.gp?ip=".$_SERVER["REMOTE_ADDR"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    $data = unserialize($data);
    mysql_query("INSERT INTO ip(ip,code) VALUES('".$_SERVER["REMOTE_ADDR"]."','".$data["geoplugin_countryCode"]."')");
}
©2009-2011 Webarto • web design & development • Tuzla // Sarajevo // Beograd