欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP禁止IP访问(不过滤搜索引擎蜘蛛)的方法

程序员文章站 2022-04-17 16:58:14
...
  1. /**

  2. * 屏蔽指定的IP地址访问,但不屏蔽搜索引擎的蜘蛛
  3. * by bbs.it-home.org
  4. */
  5. function get_ip_data(){
  6.   $ip=file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".get_client_ip());
  7.   $ip = json_decode($ip);
  8.   if($ip->code){
  9.   return false;
  10.   }
  11.   $data = (array) $ip->data;

  12.   if($data['region']=='湖北省' && !isCrawler()){
  13.   exit('http://bbs.it-home.org');
  14.   }
  15.   }
  16.   function isCrawler() {
  17.   $spiderSite= array(
  18.   "TencentTraveler",
  19.   "Baiduspider+",
  20.   "BaiduGame",
  21.   "Googlebot",
  22.   "msnbot",
  23.   "Sosospider+",
  24.   "Sogou web spider",
  25.   "ia_archiver",
  26.   "Yahoo! Slurp",
  27.   "YoudaoBot",
  28.   "Yahoo Slurp",
  29.   "MSNBot",
  30.   "Sogou Spider",
  31.   "Speedy Spider",
  32.   "Google AdSense",
  33.   "Heritrix",
  34.   "Fish search",
  35.   );
  36.   if(in_array(strtolower($_SERVER['HTTP_USER_AGENT']),$spiderSite)){

  37.   return true;
  38.   }else{
  39.   return false;
  40.   }
  41.   }
  42.   //获取客户端的IP地址
  43.   function get_client_ip()
  44.   {
  45.   if (isset($_SERVER)){
  46.   if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
  47.   $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  48.   } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
  49.   $realip = $_SERVER["HTTP_CLIENT_IP"];
  50.   } else {
  51.   $realip = $_SERVER["REMOTE_ADDR"];
  52.   }
  53.   } else {
  54.   if (getenv("HTTP_X_FORWARDED_FOR")){
  55.   $realip = getenv("HTTP_X_FORWARDED_FOR");
  56.   } else if (getenv("HTTP_CLIENT_IP")) {
  57.   $realip = getenv("HTTP_CLIENT_IP");
  58.   } else {
  59.   $realip = getenv("REMOTE_ADDR");
  60.   }
  61.   }
  62.   return $realip;
  63. }
复制代码