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

PHP Whois 查詢 API 實作:抓取新網資料與 Nginx 反向代理封裝

     編輯:PHP 綜合知識

核心思路

  1. 向新網 Whois 介面發送請求(file_get_contents 或 cURL)。
  2. 正則提取頁面關鍵資訊區塊。
  3. 3. 輸出純文本或 JSON 供前端調用。
  4. 配合 Nginx rewrite/proxy_pass 封裝為 RESTful API(/whois/{domain})。

PHP 查詢腳本 (whois.php)

<?php
$domain = isset($_GET['q']) ? trim($_GET['q']) : '';
if (!$domain) exit('Missing domain parameter');

// 簡單域名格式驗證
if (!preg_match('/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $domain)) {
    exit('Invalid domain format');
}

// 目標介面(新網)
$url = "https://www.xinnet.cn/Modules/agent/serv/pages/domain_whois.jsp?domainNameWhois={$domain}&noCode=noCode";
$html = @file_get_contents($url);
if (!$html) exit('Query failed');

// 提取內容(根據實際頁面結構調整正則)
if (preg_match('|
(.+?)
|is', $html, $match)) { // 清理 HTML 標籤、多餘空白 $result = strip_tags($match[1]); $result = preg_replace('/\s+/', ' ', $result); echo trim($result); } else { echo 'No whois data found'; } ?>

Nginx 封裝為 RESTful API

# nginx.conf
location ~* ^/whois/(.+)$ {
    # 內部轉發至 PHP 處理
    proxy_pass https://127.0.0.1:8080/whois.php?q=$1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    
    # 快取 1 小時(Whois 資料變動較慢)
    proxy_cache_valid 200 1h;
    add_header X-Cache-Status $upstream_cache_status;
}

# 或使用 rewrite 內部重寫(同一伺服器)
location /whois/ {
    rewrite ^/whois/(.+)$ /whois.php?q=$1 last;
}

前端調用範例

// JavaScript
fetch('/whois/baidu.com')
  .then(r => r.text())
  .then(console.log);

// PHP 端調用
function queryWhois($domain) {
    $ch = curl_init("https://api.example.com/whois/{$domain}");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    return curl_exec($ch);
}

生產環境強化

  • 多源備援:同時查詢萬網、ICANN、WHOIS 伺服器,合併結果。
  • 速率限制:防止被目標站封 IP,加入 Redis 計數器限流。
  • 快取策略:Whois 資料 TTL 設 24-48 小時,減少外部請求。
  • 格式標準化:輸出 JSON 結構化欄位(registrar、creation_date、expiry_date、nameservers 等)。
  • 法律合規:遵守各註冊商 Whois 使用條款,避免高頻自動化查詢被禁。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved