Skip to content

PHP getmxrr() Function: Everything You Need to Know

As a PHP developer, you may need to obtain the mail exchange (MX) records for a given domain name. In such scenarios, the getmxrr() function was historically used. Important: getmxrr() was deprecated in PHP 8.2 and removed in PHP 8.4. For modern PHP applications, use dns_get_record() instead. This article explains the legacy function for maintaining older codebases.

What is the getmxrr() Function?

The getmxrr() function performs a DNS lookup on a specified domain name and returns an array of all associated MX records. It requires the dns extension to be enabled in your PHP environment. The function returns true on success and false on failure.

How to Use the getmxrr() Function

Using the getmxrr() function is straightforward. Here is the syntax of the function:

The PHP syntax of getmxrr() Function

php
getmxrr($hostname, &$mxhosts, &$weight);

The function takes three parameters:

  • $hostname: The domain name for which you want to retrieve the MX records.
  • $mxhosts: A reference to an array that will store the MX hosts for the domain name. (Note: In PHP 5.3+, the & symbol is only required in the function signature, not when calling the function.)
  • $weight: A reference to an array that will store the MX hosts' priority weights.

Here is an example of how to use the getmxrr() function to retrieve the MX records for a domain name:

How to Use the getmxrr() Function?

php
<?php

$hostname = "example.com";
$mxhosts = [];
$weight = [];
if (getmxrr($hostname, $mxhosts, $weight)) {
  for ($i = 0; $i < count($mxhosts); $i++) {
    echo "MX record for $hostname: " . $mxhosts[$i] . ", Weight: " . $weight[$i] ;
  }
} else {
  echo "No MX record found for $hostname";
}

In this example, we retrieve the MX records for the domain name "example.com". The function performs a DNS lookup and populates the $mxhosts and $weight arrays. We then loop through the arrays and display the MX hosts and their weights. If the lookup fails, the else block handles the error gracefully.

Conclusion

The getmxrr() function is a legacy tool for retrieving MX records in older PHP versions. By understanding its syntax and behavior, you can maintain compatibility with legacy codebases. For new projects, we recommend using dns_get_record() with the DNS_MX type flag instead. We hope this article has been informative for working with historical PHP DNS functions.

Practice

What is the role of the getmxrr() function in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.