首页 > 编程语言 >php: 根据ip地址得到所属的省市

php: 根据ip地址得到所属的省市

时间:2024-08-14 11:09:26浏览次数:15  
标签:province city 省市 ipinfo ip country php response

一,代码:

说明:原代码来自于网络,我把它做了封装,去掉了其中无响应的接口,对有些地址有变化的接口做了更新,
         确保到目前为止所调用的接口都可用,
        不再直接返回json,而是返回数组

<?php
/*
根据ip得到所属的省市信息
*/
class CityByIp
{

    // 中国34个省级行政区域
    private $provinces = array(
        "北京",
        "天津",
        "河北",
        "山西",
        "内蒙古",
        "辽宁",
        "吉林",
        "黑龙江",
        "上海",
        "江苏",
        "浙江",
        "安徽",
        "福建",
        "江西",
        "山东",
        "河南",
        "湖北",
        "湖南",
        "广东",
        "广西",
        "海南",
        "重庆",
        "四川",
        "贵州",
        "云南",
        "西藏",
        "陕西",
        "甘肃",
        "青海",
        "宁夏",
        "新疆",
        "香港",
        "澳门",
        "台湾"
    );


    //构造
    public function __construct() {

    }


    //得到ip对应的省市
    function getCity($ip){

        if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
             return [
                 'code' => 201,
                 'msg' => 'ip地址错误'
            ];
        }

            // 请求接口
        $methods = [
            'getCityByCSDN',
            'getCityByIPChaxun',
            'getCityByVvhan',
            'getCityByRunoob'
        ];

        foreach ($methods as $method) {
            $response = $this->$method($ip);
            //echo $method.":\n";
            //var_dump($response);
            if ($response['code'] === 200) {
                // 如果请求成功,输出请求结果并停止循环
                //echo $method($ip);
                //break;
                return $response;
            }
        }


        //return json_encode($ipinfo,JSON_UNESCAPED_UNICODE);
        if (!isset($response) || $response['code'] !== 200) {

            $ipinfo = array(
            'code' => 201,
            'msg' => '请求失败~'
           );
            return $ipinfo;
        //echo json_encode($ipinfo,JSON_UNESCAPED_UNICODE);
        //exit;
        }
    }


    //检查ip是否合法
    function checkIpValid($ip) {
            // 验证ipv4地址合法性
       if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            return false;
        } else {
            return true;
        }
    }

    // HTTP请求封装
    function cUrlGetIP($url) {

        // cUrl
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $header[] = 'user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        return curl_exec($ch);
        curl_close($ch);
    }

    // 接口2
    // https://searchplugin.csdn.net/api/v1/ip/get?ip={ip}
    function getCityByCSDN($ip) {

        $response = $this->cUrlGetIP('https://searchplugin.csdn.net/api/v1/ip/get?ip='.$ip);
        $code = json_decode($response,true)['code'];

        if($code == 200) {

            $str1 = json_decode($response,true)['data']['address'];

            // 国家
        //return json_encode($ipinfo,JSON_UNESCAPED_UNICODE);
            $country = explode(' ', $str1)[0];

            // 省份
            $province = explode(' ', $str1)[1];

            // 城市
            $city = explode(' ', $str1)[2];

            // 县区
            $district = '';

            // 判断是否获取成功
            if($country || $province || $city || $district) {

                // 拼接数组
                $ipinfo = array(
                    'code' => 200,
                    'msg' => '获取成功',
                    'ipinfo' => array(
                        'country' => $country,
                        'province' => $province,
                        'city' => $city,
                        'district' => $district,
                        'ip' => json_decode($response,true)['data']['ip']
                    )
                );
            }else {

                $ipinfo = array(
                    'code' => 201,
                    'msg' => '获取失败'
                );
            }
        }else {

            $ipinfo = array(
                'code' => 201,
                'msg' => '获取失败'
            );
        }

        //return json_encode($ipinfo,JSON_UNESCAPED_UNICODE);
        return $ipinfo;
    }

    // 接口3
    // https://ipchaxun.com/{ip}/
    function getCityByIPChaxun($ip) {

        $response = $this->cUrlGetIP('https://ipchaxun.com/'.$ip.'/');
        $str1 = substr($response, strripos($response, "归属地") + 15);
        $str2 = substr($str1, 0, strrpos($str1, "运营商"));

        // 提取省份
        //global $provinces;
        foreach ($this->provinces as $province_) {
            if (strpos($str2, $province_) !== false) {
                $province = $province_;
                break;
            }
        }

        // 提取国家
        $str3 = substr($str2, 0, strrpos($str2, $province));
        $country = preg_replace('/[^\x{4e00}-\x{9fa5}]+/u', '', $str3);
        //return json_encode($ipinfo,JSON_UNESCAPED_UNICODE);reg_replace('/[^\x{4e00}-\x{9fa5}]+/u', '', $str3);

        // 提取城市
        $str4 = substr($str2, strripos($str2, "nofollow") + 10);
        $city = substr($str4, 0, strrpos($str4, "</a>"));

        // 提取县区
        $str6 = substr($str2, strripos($str2, "</a>") + 4);
        $district = substr($str6, 0, strrpos($str6, "</span>"));

        // 判断是否获取成功
        if($country || $province || $city || $district) {

            // 拼接数组
            $ipinfo = array(
                'code' => 200,
                'msg' => '获取成功',
                'ipinfo' => array(
                    'country' => $country,
                    'province' => $province,
                    'city' => $city,
                    'district' => $district,
                    'ip' => $ip
                )
            );
        }else {

            $ipinfo = array(
                'code' => 201,
                'msg' => '获取失败'
            );
        }

        //return json_encode($ipinfo,JSON_UNESCAPED_UNICODE);
        return $ipinfo;
    }

    // 接口4
    // https://api.vvhan.com/api/getIpInfo?ip={ip}
    // https://api.vvhan.com/api/ipInfo?ip=58.154.0.0
    function getCityByVvhan($ip) {

        //return json_encode($ipinfo,JSON_UNESCAPED_UNICODE);
        $response = $this->cUrlGetIP('https://api.vvhan.com/api/ipInfo?ip='.$ip);
        $success = json_decode($response,true)['success'];

        if($success == true) {

            $str1 = json_decode($response,true)['info'];

            // 国家
            $country = $str1['country'];

            // 省份
            $province = $str1['prov'];

            // 城市
            $city = $str1['city'];

            // 县区
            $district = '';

            // 判断是否获取成功
            if($country || $province || $city || $district) {

                // 拼接数组
                $ipinfo = array(
                    'code' => 200,
                    'msg' => '获取成功',
                    'ipinfo' => array(
                        'country' => $country,
                        'province' => $province,
                        'city' => $city,
                        'district' => $district,
                        'ip' => $ip
                    )
                );
            }else {

                $ipinfo = array(
                    'code' => 201,
                    'msg' => '获取失败'
                );
            }
        }else {

            $ipinfo = array(
                'code' => 201,
                'msg' => '获取失败'
            );
        }

        //return json_encode($ipinfo,JSON_UNESCAPED_UNICODE);
        return $ipinfo;
    }

    // 接口5
    // https://c.runoob.com/wp-content/themes/toolrunoob2/option/ajax.php?type=checkIP&REMOTE_ADDR={ip}
    // https://www.jyshare.com/wp-content/themes/toolrunoob2/option/ajax.php?type=checkIP&REMOTE_ADDR=223.72.50.231
    function getCityByRunoob($ip) {

        $response = $this->cUrlGetIP('https://www.jyshare.com/wp-content/themes/toolrunoob2/option/ajax.php?type=checkIP&REMOTE_ADDR='.$ip);

        $flag = json_decode($response,true)['flag'];

        if($flag == true) {

            $str1 = json_decode($response,true)['data'];

            // 国家
            $country = $str1['country'];

            // 省份
            $province = $str1['regionName'];

            // 城市
            $city = $str1['city'];

            // 县区
            $district = '';

            // 判断是否获取成功
            if($country || $province || $city || $district) {

                // 拼接数组
                $ipinfo = array(
                    'code' => 200,
                    'msg' => '获取成功',
                    'ipinfo' => array(
                        'country' => $country,
                        'province' => $province,
                        'city' => $city,
                        'district' => $district,
                        'ip' => $ip
                    )
                );
            }else {

                $ipinfo = array(
                    'code' => 201,
                    'msg' => '获取失败'
                );
            }
        }else {

            $ipinfo = array(
                'code' => 201,
                'msg' => '获取失败'
            );
        }

        return $ipinfo;
    }
}






$city = new CityByIp();
$ip = '120.6.106.14';
$res = $city->getCity($ip);
var_dump($res);




?>

 

二,测试效果:

liuhongdi@lhdpc:/data/work/2024_08$ php CityByIp.php 
array(3) {
  ["code"]=>
  int(200)
  ["msg"]=>
  string(12) "获取成功"
  ["ipinfo"]=>
  array(5) {
    ["country"]=>
    string(6) "中国"
    ["province"]=>
    string(6) "河北"
    ["city"]=>
    string(9) "秦皇岛"
    ["district"]=>
    string(0) ""
    ["ip"]=>
    string(12) "120.6.106.14"
  }
}

 

标签:province,city,省市,ipinfo,ip,country,php,response
From: https://www.cnblogs.com/architectforest/p/18358451

相关文章

  • 数据分析 Numpy+Scipy+Matplotlib+Pandas
    数据分析Numpy+Scipy+Matplotlib+Pandas基础数值算法科学计算数据可视化序列高级函数一、numpy是什么?1.NumericalPython,数值的Python,补充了Python语言所欠缺的数值计算能力。2.Numpy是其它数据分析及机器学习库的底层库。3.Numpy完全标准C语言实现,运行效率充分优化。......
  • 深入理解 JavaScript 闭包
    前言在JavaScript中,闭包(Closure)是一个非常强大且常见的概念,它使得函数可以访问其外部作用域中的变量,即使在该函数外部作用域已经执行完毕的情况下。闭包广泛应用于回调函数、事件处理器、模块化编程等多个场景。本文将详细探讨闭包的定义、工作原理、常见应用场景以及潜在的陷......
  • StarNet:关于 Element-wise Multiplication 的高性能解释研究 | CVPR 2024
    论文揭示了staroperation(元素乘法)在无需加宽网络下,将输入映射到高维非线性特征空间的能力。基于此提出了StarNet,在紧凑的网络结构和较低的能耗下展示了令人印象深刻的性能和低延迟来源:晓飞的算法工程笔记公众号论文:RewritetheStars论文地址:https://arxiv.org/abs/240......
  • 4.第一天(第四部分):Using IPS Device Manager
    idm初始化ids,通过https,进行连接。https://202.100.12.101设置jave分配内存-Xmx256m证书的3个test1.办法者是否可信2.时间是否有效3.url的主机名和生猪里边的cn是否匹配rdep思科私有用来传输configsdee用来传输事件告警证书是自签名的sdee由icsa研发,促进了整合的第三......
  • 3.第一天(第三部分):Getting Started with the IPS Command-Line Interface
    初始化ips清空配置erasecurrent-config擦除配置reset重启默认用户名和密码都是cisco,第一次login的时候提示你修改密码。登录方式sshconnectiontelnet默认不允许cli界面helpconft模式:#conftservicemodeservicehost(配置模式)showsettings查看系统自带配......
  • [Paper Reading] Multiple View Geometry Transformers for 3D Human Pose Estimation
    MultipleViewGeometryTransformersfor3DHumanPoseEstimationlink时间:CVPR2024机构:UniversityofToronto&&SoutheastUniversity&&MicrosoftResearchAsiaTL;DR提出一种基于Transformer端到端3DHumanPoseEstimation方法MVGFormer,核心模块是geometry与appea......
  • 【CTF | WEB】002、攻防世界WEB题目之simple_php
    文章目录simple_php题目描述:解题思路:原理simple_php题目描述:小宁听说php是最好的语言,于是她简单学习之后写了几行php代码。解题思路:打开场景<?phpshow_source(__FILE__);include("config.php");$a=@$_GET['a'];$b=@$_GET['b'];if($a==0and$a){......
  • vue使用JavaScript运算符
    第一:加法运算符{{变量+n}}<p>num参与运算{{num+12}}</p>letvm=newVue({el:"#app",data:{num:101,isOK:true,message:'你......
  • 【题解】 [NOIP 2002 普及组] 产生数
    题目描述题目大意给定\(k\)个规则,规则为“使一位数可变换成另一个一位数”。求整数\(n\)根据规则经过若干次(可以为0次或多次)变化,能生成的整数个数。思路该题主要考察:Floyd传递闭包,高精度乘法。显而易见,规则具有传递性。举个例子,1可变换成2,2可变换成3,则1可变换成3。当然......
  • node.js文件上传(图片等等...)——利用connect-multiparty中间件
    一.概念步骤讲解1.安装和引入中间件安装:通过npm安装connect-multiparty:npminstallconnect-multiparty--save。引入:在项目中引入connect-multiparty:varmultipart=require('connect-multiparty');2.基本设置配置上传目录:指定上传文件的临时存储位置,例如:app.us......