今天在论坛看到有人在问有ip要查询来源地,就整理了几种通过ip查询来源地的几种方式:
使用免费 API
function getIPLocation($ip) {
// 使用 ip-api.com 的免费 API
$apiUrl = "http://ip-api.com/json/{$ip}?lang=zh-CN";
// 发起 HTTP 请求
$response = file_get_contents($apiUrl);
if ($response === FALSE) {
return "无法查询 IP 来源地,请稍后再试。";
}
// 解析 JSON 数据
$data = json_decode($response, true);
// 检查 API 返回的状态
if ($data['status'] === 'success') {
return [
'country' => $data['country'],
'province' => $data['regionName'],
'city' => $data['city'],
'ISP' => $data['isp'],
'location' => "{$data['lat']}, {$data['lon']}",
];
} else {
return [
'country' => '未知',
'province' => '未知',
'city' => '未知',
'ISP' => '未知',
'location' => "未知",
];
}
}
提供免费api的有以下:
http://ip-api.com/json/{$ip}?lang=zh-CN
https://ipinfo.io/{$ip}/json
http://api.ipstack.com/{$ip}?access_key={$apiKey}&format=1
https://freegeoip.app/json/{$ip}
https://api.db-ip.com/v2/{$api_key}/{$ip}
https://api.ip2location.io/?key={$api_key}&ip={$ip}&format=json
具体如何解析结果看具体返回信息
使用ipgeo库
目前输为常见的有:
- 纯真 IP 数据库
- MaxMind GeoIp2 提供的免费版(GeoLite2)
- Ip2Location等,各家有各家的ip库用法
纯真ip库的用法:https://github.com/shipengtaov/qqwry-php
也可以使用composer composer require zyblog/qqwry
<?php
require 'vendor/autoload.php';
use ZYBlog\QQWry;
// 初始化 QQWry 对象
$qqwry = new QQWry('/path/to/qqwry.dat'); // 替换为你的 qqwry.dat 文件路径
// 查询 IP 地址
$ip = '180.76.76.76'; // 示例 IP 地址
$result = $qqwry->query($ip);
// 返回 JSON 格式数据
header('Content-Type: application/json');
echo json_encode([
'ip' => $ip,
'location' => $result['location'],
'ISP' => $result['isp']
], JSON_UNESCAPED_UNICODE);
?>
ip2location的用法:https://github.com/ip2location/ip2location-io-php
要先安装composer require ip2location/ip2location-io-php
$config = new \IP2LocationIO\Configuration('YOUR_API_KEY');
$ip2locationio = new IP2LocationIO\IPGeolocation($config);
$ip2locationio->lookup('8.8.8.8', 'en');
MaxMind的用法:https://github.com/maxmind/GeoIP2-php
要先安装composer require geoip2/geoip2:~2.0
function getIpLocation($ip, $lang = 'zh-CN') {
static $reader = null;
$dbFile = '/path/to/GeoLite2-City.mmdb'; // 替换为你的 GeoLite2-City.mmdb 文件路径
try {
// 单例模式提升性能
if (!$reader) {
$reader = new Reader($dbFile);
}
$record = $reader->city($ip);
$data = [
'country' => $record->country->names[$lang] ?? '未知',
'province' => $record->mostSpecificSubdivision->names[$lang] ?? '未知',
'city' => $record->city->names[$lang] ?? '未知',
'ISP' => '未知',
'location' => "{$record->location->latitude},{$record->location->longitude}"
];
return $data;
} catch (\Exception $e) {
return [
'country' => '未知',
'province' => '未知',
'city' => '未知',
'ISP' => '未知',
'location' => '未知'
];
}
}
评论