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

PHP 透過 Whois 伺服器查詢域名註冊資訊函數實作

     編輯:PHP 相關知識

PHP 透過 Whois 伺服器查詢域名註冊資訊函數實作

Whois 協定(Port 43)可查詢域名註冊人、註冊商、到期日等資訊。本文提供支援多種頂級域名(TLD)的查詢函數,自動對應官方 Whois 伺服器。

完整查詢函數

<?php
function whois_query($domain) {
  // 正規化域名
  $domain = strtolower(trim($domain));
  $domain = preg_replace('/^https?:\/\//i', '', $domain);
  $domain = preg_replace('/^www\./i', '', $domain);
  $domain = explode('/', $domain)[0];

  // 取得 TLD
  $parts = explode('.', $domain);
  $tld = end($parts);

  // TLD -> Whois 伺服器對照表(節錄常用)
  $servers = [
    'com' => 'whois.verisign-grs.com',
    'net' => 'whois.verisign-grs.com',
    'org' => 'whois.pir.org',
    'info' => 'whois.afilias.net',
    'biz' => 'whois.biz',
    'cn' => 'whois.cnnic.cn',
    'tw' => 'whois.twnic.net.tw',
    'jp' => 'whois.jprs.jp',
    'de' => 'whois.denic.de',
    'uk' => 'whois.nic.uk',
    'io' => 'whois.nic.io',
    'ai' => 'whois.nic.ai',
    'co' => 'whois.nic.co',
    'app' => 'whois.nic.google',
    'dev' => 'whois.nic.google',
    // 更多請參考 IANA 官方清單
  ];

  if (!isset($servers[$tld])) {
    throw new Exception("不支援的頂級域名: $tld");
  }

  $server = $servers[$tld];
  $response = '';

  // 連線 Port 43
  $fp = fsockopen($server, 43, $errno, $errstr, 10);
  if (!$fp) {
    throw new Exception("無法連線至 $server: $errstr ($errno)");
  }

  fputs($fp, $domain . "\r\n");
  while (!feof($fp)) {
    $response .= fgets($fp, 1024);
  }
  fclose($fp);

  return $response;
}

// 使用範例
try {
  echo whois_query('google.com');
  echo whois_query('example.org');
} catch (Exception $e) {
  echo "錯誤: " . $e->getMessage();
}
?>

關鍵點說明

  • Port 43:Whois 標準通訊埠,純文字協定。
  • 伺服器對照表:需定期更新,部分 TLD(如 .com/.net)為薄登錄,需二次查詢註冊商 Whois 才能取得完整資訊。
  • 速率限制:Whois 伺服器通常限制查詢頻率,生產環境請加入快取(Redis/Memcached)與排程更新。
  • 隱私保護:許多域名啟用 Whois Privacy,回傳資訊為代理商資訊而非真實持有者。

替代方案

  • 使用第三方 API(WhoisXML API、DomainTools、RDAP)取得結構化 JSON 資料。
  • PHP 套件:phpwhois/phpwhois(Composer 安裝),支援更多 TLD 與解析邏輯。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved