<?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=