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

使用 PHP 查詢 IP 地址歸屬地:基於 ip138 介面實現

     編輯:PHP 綜合知識

前言

在 Web 開發中,根據 IP 地址查詢地理位置是常見需求。本文展示一個簡單的 PHP 範例,透過抓取 ip138.com 的公開查詢介面,解析回傳的 HTML 內容以獲取 IP 歸屬資訊。

完整程式碼

<?php
header('Content-Type: text/html; charset=utf-8');

$ip = isset($_GET['ip']) ? trim($_GET['ip']) : '';
$msg = '';

if (isset($_GET['sub']) && $ip) {
    ipSearch($ip, $msg);
}

function ipSearch(string $ip, string &$msg) {
    // 1. 基本格式驗證
    if (substr_count($ip, '.') !== 3) {
        $msg = '無效 IP 格式,請輸入類似 192.168.1.1 的地址!';
        return;
    }
    $long = ip2long($ip);
    if ($long === false || $long === -1) {
        $msg = '無效 IP 地址,請重新輸入!';
        return;
    }

    // 2. 獲取遠端內容(注意:ip138 回傳 GB2312 編碼)
    $url = "https://www.ip138.com/ips1388.asp?action=2&ip={$ip}";
    $content = @file_get_contents($url);
    if ($content === false) {
        $msg = '無法連線至查詢服務,請稍後再試。';
        return;
    }

    // 3. 編碼轉換:GB2312 -> UTF-8
    $content = iconv('GB2312', 'UTF-8//IGNORE', $content);

    // 4. 解析目標片段
    $startTag = '
  • 本站主數據:'; $pos = stripos($content, $startTag); if ($pos === false) { $msg = '未查詢到該 IP 的歸屬資訊。'; return; } $endPos = stripos($content, '
  • ', $pos); if ($endPos === false) { $msg = '解析頁面結構異常。'; return; } $address = substr($content, $pos + strlen($startTag), $endPos - $pos - strlen($startTag)); $msg = trim($address); } // 顯示查詢表單與結果 ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>IP 歸屬地查詢</title> </head> <body> <form method="get"> <input type="text" name="ip" placeholder="請輸入 IP 地址" value="<?php echo htmlspecialchars($ip); ?>" /> <input type="submit" name="sub" value="查詢" /> </form> <br /> <div style="color: #333;"><?php echo htmlspecialchars($msg); ?></div> </body> </html>

    關鍵技術點解析

    1. IP 格式驗證:使用 substr_count() 檢查點號數量,配合 ip2long() 驗證合法性。
    2. 跨編碼處理:目標站點使用 GB2312,必須透過 iconv() 轉為 UTF-8 避免亂碼。
    3. HTML 解析策略:採用字串搜尋(stripos)定位特徵標籤,再截取內容。此法簡單但脆弱,頁面結構變更即會失效。
    4. 錯誤抑制與容錯:@file_get_contents 抑制警告,配合條件判斷給予友善提示。

    改進建議

    • 改用 cURL 替代 file_get_contents,支援超時控制、HTTPS、Header 設定等。
    • 引入成熟的 IP 地址庫(如 MaxMind GeoIP2、ip2region、QQWry.dat)實現離線高效查詢,不依賴第三方介面穩定性。
    • 增加快取機制(Redis/Memcached)減少重複查詢開銷。
    • 對輸出進行 htmlspecialchars() 轉義,防範 XSS 攻擊(範例已補全)。

    總結

    本範例演示了呼叫外部 API 並解析 HTML 回應的基本流程。實際專案中強烈建議採用離線 IP 庫或正規商業 API,以獲得更高的可用性、準確度與效能。

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