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();
}
?>
phpwhois/phpwhois(Composer 安裝),支援更多 TLD 與解析邏輯。