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);
?>

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/18/php-online-ip-address-query/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
PHP在线IP地址查询
以ip.cn为例,根据IP地址在线查询省市区 <?php $url='https://ip.cn/index.php?ip=8.8.8.8'; $data["country"] = 'unknown……
<<上一篇
下一篇>>
文章目录
关闭
目 录