由于很多人有一些需求在做国内站的时候,不做国内某个地区的业务的时候,他想屏蔽用户访问网站,我这边以dedecms搜索功能为例子,因为是以前开发的,时间比较有限现在,不重新调整做整站的功能,如果有需要,可以将以下相关代码放入一个php文件,然后在data/common.ini.php里面包含就可以了。
目前网络上有很多资源,例如著名的珊瑚虫ip数据库,但是其文件在本地,得定时更新。我们现在使用淘宝ip数据库,通过json返回的数据来解析ip是否某地区,下面以"上海市"为例:
首页找到dedecms底下plus下的search.php文件,查找以下代码
if($cfg_notallowstr !='' && preg_match("#".$cfg_notallowstr."#i", $keyword)){ ShowMsg("你的搜索关键字中存在非法内容,被系统禁止!","-1"); exit();} |
在上面加入
function get_ip_data(){ $ip=file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".get_client_ip()); $ip = json_decode($ip); if($ip->code){ return false; } $data = (array) $ip->data; if($data['city']=='上海市' && !isCrawler()){ // exit('http://www.CUOxin.com'); return true; /* header("location:".getenv("HTTP_REFERER")); // 返回其调用页面 */ }} function isCrawler() { $spiderSite= array( "TencentTraveler", "Baiduspider+", "BaiduGame", "Googlebot", "msnbot", "Sosospider+", "Sogou web spider", "ia_archiver", "Yahoo! Slurp", "YoudaoBot", "Yahoo Slurp", "MSNBot", "Java (Often spam bot)", "BaiDuSpider", "Voila", "Yandex bot", "BSpider", "twiceler", "Sogou Spider", "Speedy Spider", "Google AdSense", "Heritrix", "Python-urllib", "Alexa (IA Archiver)", "Ask", "Exabot", "Custo", "OutfoxBot/YodaoBot", "yacy", "SurveyBot", "legs", "lwp-trivial", "Nutch", "StackRambler", "The web archive (IA Archiver)", "Perl tool", "MJ12bot", "Netcraft", "MSIECrawler", "WGet tools", "larbin", "Fish search", ); if(in_array(strtolower($_SERVER['HTTP_USER_AGENT']),$spiderSite)){ return true; }else{ return false; }} //获取客户端ipfunction get_client_ip(){ if (isset($_SERVER)){ if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){ $realip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if (isset($_SERVER["HTTP_CLIENT_IP"])) { $realip = $_SERVER["HTTP_CLIENT_IP"]; } else { $realip = $_SERVER["REMOTE_ADDR"]; } } else { if (getenv("HTTP_X_FORWARDED_FOR")){ $realip = getenv("HTTP_X_FORWARDED_FOR"); } else if (getenv("HTTP_CLIENT_IP")) { $realip = getenv("HTTP_CLIENT_IP"); } else { $realip = getenv("REMOTE_ADDR"); } } return $realip;}if(get_ip_data()){ ShowMsg("你的IP被禁止!","-1"); exit();} |
保存文件后,你让上海市的朋友访问,系统就会提示"你的IP被禁止!"的提示