HomePHP Page 5 - Email Address Verification with PHP
Using getmxrr() for validation - PHP
Many applications in the field of Web development need to validate email addresses. While this can be done in a variety of ways, one simple but effective way involves writing your own functions in PHP. Alejandro Gervasio explains this approach.
It’s possible to use the getmxrr() PHP function to achieve email domain validation similar to that obtained with checkdnsrr(). This function gets MX records corresponding to a given Internet host name and has the following format:
int getmxrr ( string hostname, array mxhosts [, array weight]);
It searches the DNS for MX records corresponding to the given host name. It returns true if any records are found and returns false if no records are found or if an error occurs.
A list of the MX records found is placed into the array mxhosts. If the weight array is given, it will be filled with the weight information gathered.
Having presented this network function, it’s easily deducible that we could rewrite our checkEmail() function utilizing getmxrr() instead of checkdnsrr() to validate email domains. The revamped version is listed below:
This code looks very similar to the previous example using checkdnsrr(). The only subtle difference lies in that we have wrapped getmxrr() into the checkEmail() function. It’s a simple but powerful solution. As we can appreciate, the set of PHP network functions is an invaluable tool for validating email domains.
So far, we have defined individual functions to first, validate the proper format for an email address, and next, check whether the email domain is a real domain. From a strict point of view, this solution is still incomplete, because we really don’t know if the given user name is valid. How can this issue be addressed properly?
Actually, there is no direct way to do that. However, a fairly handy approach to help us see whether we are dealing with a valid user name might show us whether the email domain is currently in use. In that way, we can be somewhat more certain (but never completely) that someone is using that domain to send and receive email messages. This might brings us to the conclusion that the given user name is potentially valid. Let’s move to the next section to find out how we can determine this with a little extra work.