PHP IP 定位接口:获取客户端 IP、校验 IP、调用上游返回省市信息 [复制链接]

一级用户组

这是 API 站点常见的 IP 查询接口写法:自动识别客户端 IP,也支持 ?ip=8.8.8.8 手动查询。上游使用公开 JSON 服务,实际生产可以替换为自己的 IP 库或付费定位服务。

<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

function response(int $code, string $message, $data = null, int $status = 200): void
{
    http_response_code($status);
    echo json_encode(compact('code', 'message', 'data'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function client_ip(): string
{
    $headers = [
        'HTTP_CF_CONNECTING_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_REAL_IP',
        'REMOTE_ADDR',
    ];

    foreach ($headers as $header) {
        $value = $_SERVER[$header] ?? '';
        if ($value === '') {
            continue;
        }
        $ip = trim(explode(',', $value)[0]);
        if (filter_var($ip, FILTER_VALIDATE_IP)) {
            return $ip;
        }
    }

    return '127.0.0.1';
}

$ip = trim((string)($_GET['ip'] ?? client_ip()));
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
    response(422, 'IP 格式错误', null, 422);
}

$url = 'http://ip-api.com/json/' . rawurlencode($ip) . '?lang=zh-CN&fields=status,message,country,regionName,city,query,isp,org,lat,lon,timezone';
$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'timeout' => 3,
        'header' => "User-Agent: PHP-IP-API/1.0
",
    ],
]);

$raw = @file_get_contents($url, false, $context);
if ($raw === false) {
    response(502, '上游 IP 服务请求失败', null, 502);
}

$result = json_decode($raw, true);
if (!is_array($result) || ($result['status'] ?? '') !== 'success') {
    response(404, $result['message'] ?? '未查询到定位信息', null, 404);
}

response(0, 'ok', [
    'ip' => $result['query'] ?? $ip,
    'country' => $result['country'] ?? '',
    'region' => $result['regionName'] ?? '',
    'city' => $result['city'] ?? '',
    'isp' => $result['isp'] ?? '',
    'org' => $result['org'] ?? '',
    'lat' => $result['lat'] ?? null,
    'lon' => $result['lon'] ?? null,
    'timezone' => $result['timezone'] ?? '',
]);

本地测试:

# 启动服务
php -S 127.0.0.1:8000 ip-location.php

# 查询指定 IP
curl 'http://127.0.0.1:8000/ip-location.php?ip=8.8.8.8'

# 自动识别当前访问 IP
curl 'http://127.0.0.1:8000/ip-location.php'
最新回复

请先登录后再回复 登录

uid:4 一级用户组
关注
我与春风皆过客,你携秋水揽星河
发帖 20
评论 0
粉丝 0
关注 0
发新帖
目录
PHP IP 定位接口:获取客户端 IP、校验 IP、调用上游返回省市信息