[PHP]实现屏蔽某国家IP的访问

现在有个需求为[禁止某国家的IP访问网站],思路一为:先获得访问网站的IP,然后判断该IP是否为某个国家的IP,来实现该功能。

获得IP方法如下代码:

function GetIP(){
if(!empty($_SERVER["HTTP_CLIENT_IP"])){
  $cip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
  $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif(!empty($_SERVER["REMOTE_ADDR"])){
  $cip = $_SERVER["REMOTE_ADDR"];
}
else{
  $cip = "无法获取!";
}
return $cip;
}

获得IP之后然后判断该IP是属于哪个国家即可,而需要有一个IP库,或者通过get方式从ip138中获得对应地理位置信息。

20140228221939

 

思路二: 通过对.htaccess来屏蔽IP访问,实现代码如下:

Order Allow,Deny
Deny from 222.240.253
Deny from 222.240.253.122
Allow from all

这样的IP段访问就会提示:

Forbidden
You don't have permission to access / on this server.

思路三: 通过获得浏览器语言来实现屏蔽($_SERVER[“HTTP_ACCEPT_LANGUAGE”])

20140228223020

 

实现代码如下:

if(strpos(strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]),'zh-cn')!==false){
  echo "中国IP";
}else{
  echo "非中国IP";
}

Author: jhonse

Jhonse技术博客: http://blog.jhonse.com

Leave a Reply

Your email address will not be published. Required fields are marked *