PHP代码-禁止IP访问网站

如果你想要禁止某一个国家的IP访问你的网站,请使用以下PHP代码:(如果是WP把这段代码加到Header.php中)

<?php

/**

*

* test.php(屏蔽国家IP)

*

*/

$verification = '美国';//需要屏蔽国家的IP

function get_client_ip() {

$ip = $_SERVER['REMOTE_ADDR'];

if (isset($_SERVER['HTTP_X_REAL_FORWARDED_FOR']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_FORWARDED_FOR'])) {

$ip = $_SERVER['HTTP_X_REAL_FORWARDED_FOR'];

}

elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {

$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

}

elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {

$ip = $_SERVER['HTTP_CLIENT_IP'];

}

return $ip;

}

$ip = get_client_ip();//获取访客IP

$antecedents = $_SERVER['HTTP_REFERER'];//访客来路地址

$result = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);//IP数据库来自淘宝。

$address = json_decode($result,true);

//判断访客是否属于美国,是否来自百度,是否来自谷歌

if($address['data']['country'] == $verification && strpos($antecedents, 'baidu') === false && strpos($antecedents, 'google') === false){

sleep(10);//设置一个10秒等待。

header('HTTP/1.1 503 Service Temporarily Unavailable');

header('Status: 503 Service Temporarily Unavailable');

header('Retry-After: 3600000');

exit;

}

?>

如果你想要禁止某一个省份的IP访问你的网站,请使用以下PHP代码:

<?php

/**

*

* test.php(屏蔽地方IP)

*

*/

$verification = '江西省';//需要屏蔽省份的IP

function get_client_ip() {

$ip = $_SERVER['REMOTE_ADDR'];

if (isset($_SERVER['HTTP_X_REAL_FORWARDED_FOR']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_FORWARDED_FOR'])) {

$ip = $_SERVER['HTTP_X_REAL_FORWARDED_FOR'];

}

elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {

$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

}

elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {

$ip = $_SERVER['HTTP_CLIENT_IP'];

}

return $ip;

}

$ip = get_client_ip();//获取访客IP

$antecedents = $_SERVER['HTTP_REFERER'];//访客来路地址

$result = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);//IP数据库来自淘宝。

$address = json_decode($result,true);

//判断访客是否属于江西省,是否来自百度,是否来自谷歌

if($address['data']['region'] == $verification && strpos($antecedents, 'baidu') === false && strpos($antecedents, 'google') === false){

sleep(99999999);//设置一个999999秒的等待。

Header("HTTP/1.1 204 No Content");

exit;

}

?>

聪明的朋友一定发现了以上代码其实还可以精确到市一级IP,你只需要替换成city就可以了,代码引用淘宝IP库的格式如下:

你可能感兴趣的