tp5 +腾讯 ip 接口实现地区屏蔽功能

2019-06-09   阅读:3007   类型:后端   分类:TP5    标签: TP5

image.png

腾讯地图接口是用户最多的,定位也是最准确的。

以下介绍利用腾讯地图接口实现地区,ip,屏蔽功能。

前提,去https://lbs.qq.com/注册账号,申请接口,得到 APPKEY ,

思路:

获取用户 ip ,屏蔽该ip

通过接口查询ip所在位置

接口返回信息

{
    "status": 0,
    "message": "query ok",
    "result": {
        "ip": "113.69.144.60",
        "location": {
            "lat": 22.80536,
            "lng": 113.29321
        },
        "ad_info": {
            "nation": "中国",
            "province": "广东省",
            "city": "佛山市",
            "district": "顺德区",
            "adcode": 440606
        }
    }
}

后台界面效果:

配置:

image.png

IP:

image.png

地区:

image.png

建表:

//ip配置表:ba_ip_setup

CREATE TABLE `ba_ip_setup` (
  `id` int(1) NOT NULL AUTO_INCREMENT,
  `appkey` varchar(255) DEFAULT NULL COMMENT 'appkey',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

//ip表
CREATE TABLE `ba_zoos_ip` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ip` varchar(150) DEFAULT NULL,
  `addtime` int(12) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
//地区表
CREATE TABLE `ba_zoos_address` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `address` text,
  `addtime` int(12) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

前端代码:

//配置:
<form action="" class="form-horizontal" id="myForm2">
	<div class="form-group">
		<label class="col-sm-1 control-label no-padding-right" for="form-field-1"> 腾讯APPKEY: </label>
		<input type="hidden" name="id" value="{$edRes.id}">
		<div class="col-sm-10">
		   <input type="text" value="{$edRes.appkey}" name="appkey" class="col-md-5">
		</div>
	</div>
	<div class="form-group">
		<label class="col-sm-1 control-label no-padding-right" for="form-field-1"></label>
		 <div class="col-md-6">
			 <p><b>调用地址:</b>http://www.tpxhm.com/Sdk/getip</p>
		 </div>
	</div>
	<div class="form-group">
		 <label class="col-sm-1 control-label no-padding-right" for="form-field-1"></label>
		 <div class="col-md-5">
			 <button type="button" class="btn btn-sm btn-danger" onclick="zoos_setup()">提交保存</button>
		 </div>
	</div>
   
</form>
<script>
        function zoos_setup(){
             var form1 = document.getElementById("myForm2");
            var formData = new FormData(form1);
              $.ajax({
                  url:"{:url('admin/Zoos/setup')}",
                  type:'post',
                  data:formData,
                  timeout:5000,
                  datatype:'text',
                  processData: false,                  
                  contentType: false,
                  success:function(msg){
                    alert(msg.message);
                      location.reload();
                  }
                });
      } 
</script>

//ip
<div class="row">
	<div class="col-xs-12">
		<!-- PAGE CONTENT BEGINS -->
				 <a href="javascript:;" data-toggle="modal" data-target="#myModal"><button class="btn btn-primary"><i class="glyphicon glyphicon-plus"></i>添加ip</button></a>
				<div class="table-responsive">
					<table id="sample-table-1" class="table table-striped table-bordered table-hover">
						<thead>
							<tr>
								<th>ID</th>
								<th>IP</th>
								<th>添加时间</th>
								<th>操作</th>
							</tr>
						</thead>

						<tbody>
						{volist name="res" id="vo" key='k'}
							<tr>
								<td>{$k}</td>
								<td>{$vo.ip}</td>
								<td width="70%">{$vo.addtime|date='Y-m-d H:s:i',###}</td>
								<td width="7%">
									<a class="red" href="javascript:;"><i class="icon-trash bigger-130" onclick="del(this,{$vo.id})"></i></a>
								</td>
							</tr>
						{/volist}
						</tbody>
					</table>
					<div>
					<ul class="pagination pull-right no-margin">
						{$res->render()}
					</ul>
				</div>
			</div>
</div>
</div>
<script>
    function zoos_ipAdd(){
          // 获取页面已有的一个form表单
         var form1 = document.getElementById("myForm1");
        // 用表单来初始化
        var formData = new FormData(form1);
          // ajax
          $.ajax({
              url:"{:url('admin/Zoos/zoos_ipAdd')}",
              type:'post',
              data:formData,
              timeout:5000,
              datatype:'text',
              processData: false,                  
              contentType: false,
              success:function(msg){
                alert(msg.message);
                  location.reload();
              }
            });
          // ajacend
      } 
      function del(obj,obid){
            if(confirm("确认删除该IP么?")){
                $.ajax({
                url:"{:url('admin/Zoos/del')}",
                type:'post',
                data:{"id":obid},
                datatype:'json',
                success:function(msg){
                  alert(msg.message)
                  location.reload();
                }
              });
            } 
        }

</script>
//地区
 <div class="row">
	<div class="col-xs-12">
		<form action="" class="form-horizontal" id="myForm2">
			<div class="form-group">
				<label class="col-sm-1 control-label no-padding-right" for="form-field-1"> 地区: </label>
				<input type="hidden" name="id" value="{$edRes.id}">
				<div class="col-sm-10">
				   <textarea name="address" id="" cols="100" rows="15" class="col-m-12" style="width:100%;">{$edRes.address}</textarea>
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-1 control-label no-padding-right" for="form-field-1"></label>
				 <div class="col-md-6">
					 <p><b>格式【用“|”隔开】:</b>屏蔽国家:例如:中国。屏蔽地区:例如:广东省。屏蔽市:例如:广州市。屏蔽地区:例如:天河区</p>
				 </div>
			</div>
			<div class="form-group">
				 <label class="col-sm-1 control-label no-padding-right" for="form-field-1"></label>
				 <div class="col-md-5">
					 <button type="button" class="btn btn-sm btn-danger" onclick="zoos_ipaddressAdd()">提交保存</button>
				 </div>
			</div>
		   
		</form>
	</div>
</div>
<script>
        function zoos_ipaddressAdd(){
             var form1 = document.getElementById("myForm2");
            var formData = new FormData(form1);
              $.ajax({
                  url:"{:url('admin/Zoos/zoos_addressAdd')}",
                  type:'post',
                  data:formData,
                  timeout:5000,
                  datatype:'text',
                  processData: false,                  
                  contentType: false,
                  success:function(msg){
                    alert(msg.message);
                      location.reload();
                  }
                });
      } 
</script>

后台后端代码

<?php
namespace app\admin\controller;
use think\Controller;
use think\DB;
class Zoos extends Base
{
    public  function back(){
    	$res=db('zoos_ip')->order('id desc')->paginate(22);
        $this->assign('res',$res);
        return $this->fetch();
    }
    function zoos_ipAdd(){
    	if(request()->isPost()){
    		$data=input();
    		$data['addtime']=time();
    		$res=db('zoos_ip')->insert($data);
    		if($res){
    			return json(['success'=>1,'code'=>200,'message'=>'添加成功!']);
    		}else{
    			return json(['error'=>0,'code'=>500,'message'=>'添加失败!']);
    		}
    	}
    }
    public  function white(){
        $edRes=db('zoos_address')->find('1');
    	$this->assign('edRes',$edRes);
        return $this->fetch();
    }
    public function zoos_addressAdd(){
    	if(request()->isPost()){
    		$id=input('id');
    		$data=[
    			'id'=>$id,
    			'address'=>input('address'),
    		];
    		$res=db('zoos_address')->update($data);
    		if($res){
    			return json(['success'=>1,'code'=>200,'message'=>'添加成功!']);
    		}else{
    			return json(['error'=>0,'code'=>500,'message'=>'添加失败!']);
    		}
    	}
    }
    public function del(){
      $id=input('id');
      $res=db('zoos_ip')->delete($id);
      if($res){
        return json(['success'=>1,'code'=>200,'message'=>'删除成功!']);
      }else{
        return json(['error'=>0,'code'=>500,'message'=>'删除失败!']);
      }
    }
    public function setup(){
        if(request()->isPost()){
            $id=input('id');
            $data=[
                'id'=>$id,
                'appkey'=>input('appkey'),
            ];
            $res=db('ip_setup')->update($data);
            if($res){
                return json(['success'=>1,'code'=>200,'message'=>'保存成功!']);
            }else{
                return json(['error'=>0,'code'=>500,'message'=>'保存失败!']);
            }
        }
        $edRes=db('ip_setup')->find('1');
        $this->assign('edRes',$edRes);
        return $this->fetch();
    }
}

前台调用代码:

<script type='text/javascript' src='http://www.tpxhm.com/index/Sdk/getip'></script>

php屏蔽代码:

<?php

namespace app\index\controller;
use think\Controller;
use think\DB;
header("Access-Control-Allow-Origin:*");
class Sdk extends Base{
    public function getip(){
    	$res_address=db('zoos_address')->field('address')->find();
    	$safe_address=explode("|",$res_address['address']);
    	// $safe_address=implode(',',$res_address_value); //屏蔽ip地区
    	// halt($res_address_value);
    	$res_ip=db('zoos_ip')->field('ip')->select();
    	foreach($res_ip as $k=>$v){
    		$res_ips[]=$v['ip'];
    	}
    	$safe_ip=$res_ips; //屏蔽ip
    	// 获取客户端ip
		if ($_SERVER["HTTP_X_FORWARDED_FOR"]==""){
			$user_ip=$_SERVER["REMOTE_ADDR"];
		}else{
			$user_ip=$_SERVER["HTTP_X_FORWARDED_FOR"];
		}
		// ip屏蔽判断
		if(in_array($user_ip,$safe_ip)){
			echo "window.location.href='https://www.baidu.com/404.html';";
			// echo '1';
			 // echo "<script>while(true){ window.location.href='https://www.baidu.com/';}</script>";
		}
		// 地区判断
            $edRes=db('ip_setup')->find('1'); 
      			$appkey=$edRes['appkey'];
            $api_url="https://apis.map.qq.com/ws/location/v1/ip?ip=$user_ip&key=$appkey";
            $result = $this->https_request($api_url);
            $jsonarr = json_decode($result, true);
            $result=$jsonarr['result']['ad_info'];
            if(!empty($result['nation'])){
            	$nation=$result['nation']; //国家
                if(in_array($nation,$safe_address)){
                  echo "window.location.href='https://www.baidu.com/404.html';";
                   // echo "<script>while(true){ window.location.href='https://www.baidu.com/404.html';}</script>";
                }
            }
            if(!empty($result['province'])){
            	$province=$result['province']; //省份
              if(in_array($province,$safe_address)){
                echo "window.location.href='https://www.baidu.com/404.html';";
                 // echo "<script>while(true){ window.location.href='https://www.baidu.com/404.html';}</script>";
              }
            }
             if(!empty($result['city'])){
            	$city=$result['city']; //城市
              if(in_array($city,$safe_address)){
                  echo "window.location.href='https://www.baidu.com/404.html';";
                   // echo "<script>while(true){ window.location.href='https://www.baidu.com/404.html';}</script>";
                }
            }
             if(!empty($result['district'])){
            	$district=$result['district']; //地区
              if(in_array($district,$safe_address)){
                echo "window.location.href='https://www.baidu.com/404.html';";
                 // echo "<script>while(true){ window.location.href='https://www.baidu.com/404.html';}</script>";
              }
            }
    }
        //POST提交
    public function https_request($url,$data = null){
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
      if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
      }
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      $output = curl_exec($curl);
      curl_close($curl);
      return $output;
    }


}

其实屏蔽ip还有就是服务器方面的屏蔽,各位读者可以去研究下。

腾讯云11.11上云拼团Go,2核2G3M云服务器 28元/年

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://tpxhm.com/adetail/140.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸一
简忆博客壁纸二
简忆博客壁纸三
简忆博客壁纸四
简忆博客壁纸五
简忆博客壁纸六
简忆博客壁纸七
简忆博客壁纸八
头像

简忆博客
勤于学习,乐于分享

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×