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 使用Spring Cloud Sleuth和Zipkin进行分布式链路跟踪
使用Spring Cloud Sleuth和Zipkin进行分布式链路跟踪
2
JS遍历对象、map及数组
JS遍历对象、map及数组
3
Spring Security OAuth2之认证服务、资源服务、web安全配置服务加载优先级详解
Spring Security OAuth2之认证服务、资源服务、web安全配置服务加载优先级详解
4
Spring Cloud Gateway 动态路由 - 进阶
Spring Cloud Gateway 动态路由 - 进阶
5
VuePress图片资源中文路径问题
VuePress图片资源中文路径问题
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。