首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 整合淘寶 IP 地址庫查詢類封裝

     編輯:PHP 相關知識

服務介紹

淘寶開放平台提供免費 IP 地理信息查詢接口:https://ip.taobao.com/service/getIpInfo.php?ip=,返回 JSON 格式數據,包含國家、地區、城市、ISP 等字段,適合會員註冊記錄、訪問統計、風控等場景。

封裝類實現 (TaobaoIPQuery.php)

<?php
class TaobaoIPQuery {
    private string $ip;
    private ?object $data = null;
    private const API_URL = 'https://ip.taobao.com/service/getIpInfo.php';
    private const TIMEOUT = 3.0;

    public function __construct(string $ip) {
        if (empty($ip)) throw new InvalidArgumentException('IP address must not be empty');
        $this->ip = $ip;
        $this->fetch();
    }

    private function fetch(): void {
        $url = self::API_URL . '?ip=' . urlencode($this->ip);
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => self::TIMEOUT,
            CURLOPT_SSL_VERIFYPEER => false, // HTTP 接口無需 SSL
        ]);
        $response = curl_exec($ch);
        $errno    = curl_errno($ch);
        curl_close($ch);

        if ($errno) throw new RuntimeException("cURL error ($errno): " . curl_error($ch));
        if (!$response) throw new RuntimeException('Empty response from Taobao IP API');

        $json = json_decode($response);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException('JSON decode failed: ' . json_last_error_msg());
        }
        if (!isset($json->code) || $json->code !== 0) {
            throw new RuntimeException('API error: ' . ($json->msg ?? 'Unknown'));
        }
        $this->data = $json->data;
    }

    public function getCountry(): string { return $this->data->country ?? ''; }
    public function getRegion(): string  { return $this->data->region ?? ''; }
    public function getCity(): string    { return $this->data->city ?? ''; }
    public function getIsp(): string     { return $this->data->isp ?? ''; }
    public function getArea(): string    { return $this->data->area ?? ''; }
    public function getIp(): string      { return $this->data->ip ?? $this->ip; }
    
    public function getAll(): array {
        return (array)$this->data;
    }
}

使用示例

<?php
require_once 'TaobaoIPQuery.php';

try {
    $clientIp = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    // 取第一個非 unknown IP
    $clientIp = array_shift(array_filter(explode(',', $clientIp), fn($ip) => trim($ip) !== 'unknown'));
    
    $query = new TaobaoIPQuery(trim($clientIp));
    
    echo "國家: {$query->getCountry()}\n";
    echo "地區: {$query->getRegion()}\n";
    echo "城市: {$query->getCity()}\n";
    echo "ISP : {$query->getIsp()}\n";
    
    // 入庫示例
    $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
    $stmt = $pdo->prepare("INSERT INTO user_logins (ip, country, region, city, isp, created_at) VALUES (?,?,?,?,?,NOW())");
    $stmt->execute([
        $query->getIp(),
        $query->getCountry(),
        $query->getRegion(),
        $query->getCity(),
        $query->getIsp(),
    ]);
} catch (Exception $e) {
    error_log('IP 查詢失敗: ' . $e->getMessage());
    // 降級處理:記錄原始 IP,不阻塞主流程
}

生產環境優化建議

  • 本地快取:Redis 緩存 IP 查詢結果 (TTL 30 天),減少外部請求延遲
  • 異步處理:將查詢放入消息隊列,不阻塞用戶請求
  • 備用接口:整合新浪 https://ipapi.sinaapp.com/、IP2Location 等多源切換
  • HTTPS 升級:淘寶接口現已支援 HTTPS,建議使用 https://ip.taobao.com/
  • 頻率限制:淘寶接口有 QPS 限制,高併發需自建 IP 庫 (如 MaxMind GeoIP2)

替代方案:Composer 套件

composer require torann/geoip
// 或
composer require geoip2/geoip2:~2.0 (MaxMind 官方)

離線資料庫查詢零延遲、無外部依賴,適合高頻場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved