checkdnsrr() 僅在 Linux/Unix 可用,Windows 版 PHP 缺失此函數。跨平台項目需自行實現兼容層。
if (!function_exists('checkdnsrr')) {
/**
* 檢查 DNS 記錄(Windows 兼容實現)
* @param string $host 主機名或 IP
* @param string $type 記錄類型:A, MX, NS, TXT, CNAME, AAAA, ANY 等
* @return bool
*/
function checkdnsrr($host, $type = 'MX') {
if (empty($host) || empty($type)) return false;
// 逃逸參數防命令注入
$host = escapeshellarg($host);
$type = escapeshellarg($type);
// Windows nslookup 語法:nslookup -type=TYPE HOST
$cmd = "nslookup -type=$type $host";
@exec($cmd, $output, $returnVar);
// nslookup 非 0 返回碼通常表示查詢失敗
if ($returnVar !== 0) return false;
// 解析輸出,判斷是否包含有效記錄
foreach ($output as $line) {
// 簡單匹配:包含查詢的主機名且非錯誤提示
if (stripos($line, $host) !== false &&
stripos($line, 'non-existent') === false &&
stripos($line, 'NXDOMAIN') === false &&
stripos($line, 'timeout') === false) {
return true;
}
}
return false;
}
}
function dns_get_record_compat($host, $type = 'A') {
if (!function_exists('dns_get_record')) {
// 簡易實現:調用 nslookup 並解析輸出
$cmd = "nslookup -type=" . escapeshellarg($type) . " " . escapeshellarg($host);
@exec($cmd, $output);
$records = [];
foreach ($output as $line) {
// 簡單解析 A/AAAA/MX/TXT/NS/CNAME 行
// 實際項目建議直接要求 Linux 環境或安裝 php-dns 擴展
}
return $records;
}
return dns_get_record($host, $type);
}
react/dns(異步)、php-dns 擴展,而非依賴系統 nslookup/dig。Windows 下 checkdnsrr 缺失是歷史遺留問題。現代 PHP 專案應**統一 Linux 運行環境**,若必須支援 Windows,請使用上述兼容層並充分測試邊界情況(超時、權限、編碼)。長遠看,容器化與遷移至 Linux 是成本最低、穩定性最高的選擇。