Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Verify if email is from a valid domain in PHP

Working on an application which received user signups and let’s suppose it’s built on top of PHP, you want to validate that the email the user enters is valid. Sure, you’ll check that the email entered is a “syntactically” valid one by using one of these methods.

But, what if, let’s say, you also want to verify the email in question comes from a valid domain. i.e it’s not something non-existent such as [email protected] where iamjusttestingforthesackoftesting.com doesn’t exist at all on the internet.

There’s a handy little function in PHP that let’s you do just that.

The checkdnsrr function

What you’d do is parse domain of the email using checkdnsrr like so.

$emailArray = explode("@", "[email protected]");

if (checkdnsrr(array_pop($emailArray), "MX")) {
    print "valid email domain";
} else {
    print "invalid email domain";
}

What happens here is, the checkdnsrr checks DNS records of given type (“MX” in this case) corresponding to a given email address. Here, “MX” is a mail exchanger record (MX record) specifies the mail server responsible for accepting email messages on behalf of a domain name. If bar.com domain exists in the above example, the funtion will return true.

You’d however need to check if the email is a valid “syntactically” before applying the above check for the domain existence because checkdnsrr will expect a fully qualified name in order to lookup for the MX records.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?