登录
原创

快速实现IP地址归属地在线查询功能

发布于 2020-10-22 阅读 3992
  • 后端
  • CSS
  • HTML
  • jQuery
  • PHP
原创

前期准备

判断IP归属地可以通过聚合数据提供地一个免费接口进行获取结果,https://www.juhe.cn/docs/api/id/1
由于提供的接口,不支持跨域请求,所以我们通过PHP进行请求,将结果返回前端页面展示。当然也可以通过Java、Python、Go等语言实现

服务端代码 server.php

请求接口部分代码,直接使用提供的代码示例:https://www.sdk.cn/details/vjxQ9bLPEpE7bqnKOZ

<?php
header('Content-type:text/html;charset=utf-8');

// 获取需要查询到IP地址,如果没有传递默认获取客户端当前IP
$ip = isset($_REQUEST['ip']) ? $_REQUEST['ip'] : null;
$ipLocationResult = getIPLocation($ip);

// 结果转为JSON格式,返回前端
$ipLocationResultJson = json_encode($ipLocationResult, JSON_UNESCAPED_UNICODE);

echo $ipLocationResultJson;

/**
 * 调用聚合数据提供的接口,进行查询IP归属地结果
 * 接口请求Key,可以通过https://www.juhe.cn/docs/api/id/1免费申请开通
 */
function getIPLocation($ip)
{
    // 接口请求Key
    $appkey = '*******';

    //根据查询的IP地址,查询该IP所属的区域
    $url = "http://apis.juhe.cn/ip/ipNew";
    $params = [
        "ip" => $ip,//需要查询的IP地址
        "key" => $appkey,//在聚合申请到到接口请求Key
    ];
    $paramstring = http_build_query($params);
    $content = juheHttpRequest($url, $paramstring, 1);
    $result = json_decode($content, true);
    if ($result) {
        if ($result['error_code'] == 0) {
            // echo "国家:{$result['result']['Country']}" . PHP_EOL;
            // echo "省份:{$result['result']['Province']}" . PHP_EOL;
            // echo "城市:{$result['result']['City']}" . PHP_EOL;
            // echo "运营商:{$result["result"]['Isp']}" . PHP_EOL;

            // 查询成功
            return ["code" => "1", "msg" => "查询成功", "data" => $result["result"]];
        } else {
            // 查询失败
            return ["code" => "-1", "msg" => "{$result['error_code']}:{$result['reason']}"];
        }
    } else {
        // 请求结果无响应或非正常响应内容;
        return ["code" => "-1", "msg" => "网络异常,请求失败"];
    }
}


/**
 * 请求接口返回内容
 * @param string $url [请求的URL地址]
 * @param string $params [请求的参数]
 * @param int $ipost [是否采用POST形式]
 * @return  string
 */
function juheHttpRequest($url, $params = false, $ispost = 0)
{
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}

前端请求代码 test.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://juhecdn.oss-cn-hangzhou.aliyuncs.com/css/reset.css">

    <script src="https://juhecdn.oss-cn-hangzhou.aliyuncs.com/jquery/jquery.min.js"></script>
    <script src="https://juhecdn.oss-cn-hangzhou.aliyuncs.com/jquery/jquery.form.min.js"></script>
    <script src="https://juhecdn.oss-cn-hangzhou.aliyuncs.com/jquery/json.parse.js"></script>

    <title>IP地址归属地在线查询功能演示</title>
    <style>
        input, select, textarea {
            font-family: Tahoma, Helvetica, "microsoft yahei", "Hiragino Sans GB", Simsun, \5b8b\4f53, sans-serif;
            -webkit-font-smoothing: antialiased;
        }

        input[type="text"], input[type="password"], input[type="number"], input[type="date"], input[type="time"], textarea, select {
            background-color: #fff;
            border: 1px solid #ccc;
            -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
            -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
            box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
            -webkit-transition: border linear .2s, box-shadow linear .2s;
            -moz-transition: border linear .2s, box-shadow linear .2s;
            -o-transition: border linear .2s, box-shadow linear .2s;
            transition: border linear .2s, box-shadow linear .2s;
            color: #666666
        }

        input[type="text"]:focus, input[type="password"]:focus, input[type="number"]:focus, input[type="date"]:focus, input[type="time"]:focus, textarea:focus, select:focus {
            border-color: rgba(82, 168, 236, 0.8);
            outline: 0;
            outline: thin dotted \9;
            -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
            -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
            box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6)
        }

        textarea {
            font-family: Tahoma, Geneva, sans-serif, "Microsoft Yahei";
            margin: 10px 0px 10px 0px;
            color: #333
        }

        .main {
            width: 450px;
            margin: 0 auto;
            height: 100%;
        }

        .main .phoneMain {
            width: 99%;
            margin: 0 auto;
            text-align: center;
        }

        .main .phoneMain .pm {
            width: 100%;
        }

        .main .phoneMain .pmLeft {
            width: 79%;
            float: left;
        }

        .main .phoneMain .pmRight {
            width: 20%;
            float: right;
        }

        .clearfix {
            clear: both;
        }

        #ip {
            height: 40px;
            line-height: 40px;
            width: 100%;
            color: #333;
            font-size: 12px;
            text-indent: 5px;
            border-radius: 4px;
        }

        .custom-btn {
            border: 1px solid #5bb1e4;
            width: 100%;
            color: #FFF;
            height: 42px;
            line-height: 42px;
            background: #5bb1e4;
            cursor: pointer;
            outline: 0;
            border-radius: 4px;
        }

        .api_table {
            margin-top: 10px;
            width: 100%;
            font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
            font-size: 12px;
            border-right: 1px solid #8fbcd8;
            border-left: 1px solid #8fbcd8;
            border-top: 1px solid #8fbcd8;
        }

        .api_table th {
            text-align: left;
            font-weight: 400;
            border-bottom: 1px solid #8fbcd8;
            color: #555;
            height: 40px;
            line-height: 40px;
        }

        .api_table td {
            line-height: 40px;
            color: #646466;
            border-bottom: 1px solid #8fbcd8;
            border-right: 1px solid #8fbcd8;
            text-align: center
        }

        .api_table tr.title {
            background: #5bb1e4;
            height: 40px;
            line-height: 40px;
            font-weight: bolder;
            color: #ffffff;
        }

        .api_table a {
            cursor: pointer;
        }

        .api_table tr.trres:nth-child(odd) {
            background: #FFFFFF;
        }

        .api_table tr.trres:nth-child(even) {
            background: #f5f6fa;
        }

        .api_table a {
            color: #5bb1e4;
        }

        @media only screen and (max-width: 640px) {
            .main {
                width: 100%;
            }
        }

        .logo {
            height: 10px;
        }
    </style>
</head>
<body>
<div class="main">
    <div class="phoneMain">
        <div class="logo">
        </div>
        <div class="pm">
            <form name="singleForm" id="singleForm" action="server.php" method="post">
                <div class="pmLeft"><input type="text" name="ip" value="" id="ip" placeholder="请输入要查询的IP地址"
                                           class="woinput"></div>
                <div class="pmRight"><input type="button" value="查询" class="custom-btn" id="singleBtn"></div>
                <div class="clearfix"></div>
            </form>
        </div>
        <div>
            <table class="api_table">
                <tr class="title">
                    <td colspan="2" align="center" style="color: #FFF">+++查询结果+++</td>
                </tr>
                <tr>
                    <td width="120">IP地址</td>
                    <td><span id="resIP"></span></td>
                </tr>
                <tr>
                    <td>国家/地区</td>
                    <td><span id="resLoc"></span></td>
                </tr>
                <tr>
                    <td>省份</td>
                    <td><span id="resProvince"></span></td>
                </tr>
                <tr>
                    <td>城市</td>
                    <td><span id="resCity"></span></td>
                </tr>
                <tr>
                    <td>运营商</td>
                    <td><span id="resSp"></span></td>
                </tr>

            </table>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $("#singleBtn").click(function () {
            $("#resIP,#resLoc,#resSp,#resProvince,#resCity").html('...');
            var patt = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/i
            var ip = $("#ip").val();
            var isValidIp = patt.test(ip);
            if (!isValidIp) {
                $("#resIP").html("<span style='color:red'>IP地址格式不正确</span>");
                $("#resLoc,#resSp,#resProvince,#resCity").html('');
            } else {
                $(this).attr("disabled", "disabled").val('查询中...');
                $("#singleForm").ajaxSubmit(function (e) {
                    // console.log(ip)
                    var obj = json_parse(e);
                    var code = obj.code;
                    if (code != '1') {
                        $("#resIP").html("<span style='color:red'>" + obj.msg + "</span>");
                        $("#resLoc,#resSp,#resProvince,#resCity").html('');
                    } else {
                        $("#resIP").html(ip);
                        $("#resLoc").html(obj.data.Country);
                        $("#resSp").html(obj.data.Isp);
                        $("#resProvince").html(obj.data.Province);
                        $("#resCity").html(obj.data.City);
                    }
                    $("#singleBtn").removeAttr("disabled").val("查询");
                })
            }
        })

    })
</script>
</body>
</html>

展示效果

image.png

评论区

励志做一条安静的咸鱼,从此走上人生巅峰。

0

0

0

举报