PHP在线IP地址查询

ip.cn为例,根据IP地址在线查询省市区

<?php
$url='https://ip.cn/index.php?ip=8.8.8.8';

$data["country"] = 'unknown';
$data["region"] = 'unknown';
$data["city"] = 'unknown';

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT ,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.113 Safari/537.36");
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$html = curl_exec($ch);

if (preg_match_all('%<p.*?>(.*?)</p>%si', $html, $matches)) {
    $arr[0][] = $matches[1];
}
if ($arr[0][0][2] && strpos($arr[0][0][2], 'GeoIP') !== FALSE) {
    $geoip = str_replace("GeoIP:", "", $arr[0][0][2]);
    $geo_arr = explode(",", $geoip);
    if (count($geo_arr) == 3) {
        $data['country'] = trim($geo_arr[2]);
        $data['region'] = trim($geo_arr[1]);
        $data['city'] = trim($geo_arr[0]);
    }
    if (count($geo_arr) == 1) {
        $data['country'] = trim($geo_arr[0]);
    }
    if (count($geo_arr) == 2) {
        $data['country'] = trim($geo_arr[1]);
        $data['region'] = trim($geo_arr[0]);
    }
} else if ($arr[0][0][3] && strpos($arr[0][0][3], 'GeoIP') !== FALSE) {  //过滤广告
    $geoip = str_replace("GeoIP:", "", $arr[0][0][3]);
    $geo_arr = explode(",",$geoip);
    if (count($geo_arr) == 3) {
        $data['country'] = trim($geo_arr[2]);
        $data['region'] = trim($geo_arr[1]);
        $data['city'] = trim($geo_arr[0]);
    }
    if (count($geo_arr) == 1) {
        $data['country'] = trim($geo_arr[0]);
    }
    if (count($geo_arr) == 2) {
        $data['country'] = trim($geo_arr[1]);
        $data['region'] = trim($geo_arr[0]);
    }
}

var_dump($data);
?>
上一篇 PHP查找字符串
下一篇 PHP安装igbinary和redis扩展
目录
文章列表
1 RxJava2学习之六:登录后再获取用户信息
RxJava2学习之六:登录后再获取用户信息
2
Nacos实现Spring Cloud Gateway的动态路由
Nacos实现Spring Cloud Gateway的动态路由
3
Windows终端命令行下使用SSR代理
Windows终端命令行下使用SSR代理
4
CentOS 7 升级 gcc 和 g++
CentOS 7 升级 gcc 和 g++
5
Logstash使用日志记录时间替换@timestamp
Logstash使用日志记录时间替换@timestamp
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。