PHP dns_get_mx 函数
最后修改于 2025 年 4 月 4 日
PHP dns_get_mx 函数用于检索给定主机的 MX(邮件交换)记录。它对于电子邮件服务器配置和验证至关重要。
基本定义
dns_get_mx 获取指定互联网主机的 MX 记录。MX 记录标识负责接收电子邮件消息的邮件服务器。
语法:dns_get_mx(string $hostname, array &$hosts, array &$weights = null): bool。成功返回 true,失败返回 false。使用主机和权重填充数组。
基本 MX 记录查找
此示例演示了 dns_get_mx 的最简单用法,用于获取域的 MX 记录。
basic_mx_lookup.php
<?php
declare(strict_types=1);
$domain = "example.com";
$mxhosts = [];
$mxweights = [];
if (dns_get_mx($domain, $mxhosts, $mxweights)) {
echo "MX records for $domain:\n";
print_r($mxhosts);
} else {
echo "No MX records found for $domain";
}
此代码检查 MX 记录并在找到时打印邮件服务器。该函数使用服务器名称填充 $mxhosts 数组。
显示带优先级的 MX 记录
此示例展示了如何显示 MX 主机及其优先级权重。
mx_with_weights.php
<?php
declare(strict_types=1);
$domain = "gmail.com";
$mxhosts = [];
$mxweights = [];
if (dns_get_mx($domain, $mxhosts, $mxweights)) {
echo "MX records for $domain:\n";
foreach ($mxhosts as $key => $host) {
echo "Host: $host, Priority: {$mxweights[$key]}\n";
}
} else {
echo "No MX records found for $domain";
}
MX 记录具有优先级(权重),这些优先级决定了邮件服务器使用顺序。在电子邮件递送中,较低的数字表示较高的优先级。
电子邮件域验证
此示例创建一个函数,通过检查 MX 记录来验证域是否可以接收电子邮件。
email_domain_validator.php
<?php
declare(strict_types=1);
function isValidEmailDomain($email): bool {
$parts = explode('@', $email);
if (count($parts) != 2) return false;
$domain = $parts[1];
$mxhosts = [];
return dns_get_mx($domain, $mxhosts);
}
$email = "user@example.com";
echo isValidEmailDomain($email) ? "Valid domain" : "Invalid domain";
此函数拆分电子邮件地址以提取域部分。然后它检查域是否已配置 MX 记录以接收电子邮件。
按优先级对 MX 记录进行排序
此示例演示了按优先级权重对 MX 记录进行排序以正确选择邮件服务器。
sorted_mx_records.php
<?php
declare(strict_types=1);
$domain = "yahoo.com";
$mxhosts = [];
$mxweights = [];
if (dns_get_mx($domain, $mxhosts, $mxweights)) {
array_multisort($mxweights, $mxhosts);
echo "Sorted MX records for $domain:\n";
foreach ($mxhosts as $key => $host) {
echo "{$mxweights[$key]}: $host\n";
}
} else {
echo "No MX records found for $domain";
}
邮件服务器应按优先级顺序联系。此代码使用 array_multisort 按权重对主机进行排序。
检查多个域
此示例一次性检查多个域的 MX 记录。
multiple_domains_check.php
<?php
declare(strict_types=1);
$domains = ["google.com", "microsoft.com", "example.com"];
foreach ($domains as $domain) {
$mxhosts = [];
if (dns_get_mx($domain, $mxhosts)) {
echo "$domain has ".count($mxhosts)." MX records\n";
} else {
echo "$domain has no MX records\n";
}
}
当您需要验证多个电子邮件域或检查多个域的邮件服务器配置时,此批量处理方法很有用。
最佳实践
- 缓存:缓存 MX 查找以减少 DNS 查询
- 错误处理:优雅地处理 DNS 查找失败
- 超时:考虑为 DNS 查询设置超时
- 验证:与其他电子邮件验证方法结合使用
- 安全:清理输入以防止 DNS 投毒
来源
本教程通过 MX 记录查找和电子邮件域验证场景的实际示例,介绍了 PHP dns_get_mx 函数。
作者
列出 所有 PHP 网络函数。