ZetCode

PHP getmxrr 函数

最后修改于 2025 年 4 月 4 日

PHP 的 getmxrr 函数用于检索给定主机的 MX 记录。它对于电子邮件服务器验证和配置检查至关重要。

基本定义

getmxrr 获取主机名的 MX(邮件交换)记录。 MX 记录指定负责接收电子邮件消息的邮件服务器。

语法:getmxrr(string $hostname, array &$hosts, array &$weights = null): bool。 如果记录存在,则返回 true,否则返回 false。 需要 DNS 服务器访问。

基本 MX 记录检查

此示例检查一个域是否有 MX 记录并显示它们。

basic_mx_check.php
<?php

declare(strict_types=1);

$domain = "example.com";
$mxhosts = [];
$weights = [];

if (getmxrr($domain, $mxhosts, $weights)) {
    echo "MX records for $domain:\n";
    foreach ($mxhosts as $i => $host) {
        echo "$host (priority: {$weights[$i]})\n";
    }
} else {
    echo "No MX records found for $domain";
}

这会检查 MX 记录并显示每个邮件服务器及其优先级。 较低的优先级数字表示首选邮件服务器。

电子邮件域验证

这演示了通过检查 MX 记录来验证电子邮件域。

email_validation.php
<?php

declare(strict_types=1);

function isValidEmailDomain($email) {
    $parts = explode('@', $email);
    if (count($parts) != 2) return false;
    
    $domain = $parts[1];
    return getmxrr($domain, $mxhosts);
}

$email = "user@example.com";
echo isValidEmailDomain($email) ? "Valid email domain" : "Invalid email domain";

此函数拆分电子邮件以提取域名,然后检查 MX 记录。 这比简单的格式验证更可靠。

获取带有优先级的 MX 记录

此示例检索并按其优先级值对 MX 记录进行排序。

sorted_mx_records.php
<?php

declare(strict_types=1);

$domain = "example.com";
$mxhosts = [];
$weights = [];

if (getmxrr($domain, $mxhosts, $weights)) {
    $records = array_combine($mxhosts, $weights);
    asort($records);
    
    echo "Sorted MX records for $domain:\n";
    foreach ($records as $host => $priority) {
        echo "Priority $priority: $host\n";
    }
} else {
    echo "No MX records found for $domain";
}

这会将主机和权重合并到一个数组中,按优先级排序,并显示结果。 排序有助于识别首选邮件服务器。

检查多个域

这展示了如何在一个操作中检查多个域的 MX 记录。

multiple_domains.php
<?php

declare(strict_types=1);

$domains = ["example.com", "google.com", "nonexistent.test"];
$results = [];

foreach ($domains as $domain) {
    $results[$domain] = getmxrr($domain, $mxhosts) ? 
        "Has MX records" : "No MX records";
}

print_r($results);

这会一次检查多个域并将结果存储在数组中。 批量处理在验证多个电子邮件域时非常有效。

高级电子邮件验证

这结合了 MX 记录检查和额外的电子邮件验证步骤。

advanced_email_check.php
<?php

declare(strict_types=1);

function validateEmail($email) {
    // Basic format check
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false;
    }
    
    // Extract domain
    $domain = substr(strrchr($email, "@"), 1);
    
    // Check MX records
    if (!getmxrr($domain, $mxhosts)) {
        // Fallback to A record check
        return checkdnsrr($domain, "A");
    }
    
    return true;
}

$email = "user@example.com";
echo validateEmail($email) ? "Valid email" : "Invalid email";

这种全面的验证检查电子邮件格式、MX 记录,如果不存在 MX 记录,则回退到 A 记录。 提供强大的电子邮件验证。

最佳实践

来源

PHP getmxrr 文档

本教程涵盖了 PHP 的 getmxrr 函数,并提供了用于电子邮件验证和 MX 记录检查的实用示例。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 PHP 网络函数