查ip所在地区php源码

<?php

function queryIP($ip) {
    $filename = 'ip.merge.txt'; // 存储 IP 数据库文件名
    $handle = fopen($filename, 'r');

    if ($handle) {
        while (($line = fgets($handle)) !== false) {
            $segments = explode('|', $line);
            $startIP = $segments[0];
            $endIP = $segments[1];
            $province = $segments[4];
            $city = $segments[5];

            if (ip2long($ip) >= ip2long($startIP) && ip2long($ip) <= ip2long($endIP)) {
                fclose($handle);
                return array('ip' => $ip, 'pro' => $province, 'city' => $city, 'isp' => $segments[6]);
            }
        }

        fclose($handle);
    }

    return null;
}

// 获取用户提交的 IP
$ip = $_GET['ip'];

// 查询 IP 位置信息
$result = queryIP($ip);

if ($result) {
    $response = array(
        'msg' => '获取成功',
        'data' => array(
            'ip' => $result['ip'],
            'pro' => $result['pro'],
            'city' => $result['city'],
            'isp' => $result['isp'],
            'addr' => $result['pro'] . $result['city'] . ' ' . $result['isp']
        ),
        'statu' => 'true',
        'ip' => 'http://' . $result['ip'],
        'code' => '200'
    );
} else {
    $response = array(
        'msg' => '未找到该IP地址的位置信息。',
        'statu' => 'false',
        'code' => '404'
    );
}

// 将中文字符进行 Unicode 转义
$response = json_encode($response, JSON_UNESCAPED_UNICODE);

// 输出 JSON 格式的响应
header('Content-Type: application/json');
echo $response;
?>
 

ip.merge.txt下载地址:ip.merge.txt - 蓝奏云

输入直接查询:

你的域名/ip.php?ip=

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值