Php function for validating email addresses

To do this, we can use a couple of PHP lookup functions that come in handy for addressing these problems.The checkdnsrr() function checks DNS records corresponding to a given Internet host name or IP address.

php function for validating email addresses-79php function for validating email addresses-19

In this article, we’ll develop a reusable step-by-step solution to validate a user’s email address as accurately as possible, in an attempt to save some work the next time an application needs to check for email validity.

The process will show the power of some interesting PHP built-in network functions, as well as demonstrate how to reduce noticeably the possibilities of dirtying our applications with user-supplied bogus email.

If the application is going to make use of a basic level of validation, a quick-and-dirty way to handle the situation might be to implement a simple PHP function that performs pattern matching to a standardized email address format, as we have seen many times.

However, when a deeper and more complex validation is required, we should take a look at well-trusted validation classes, such as Pear’s HTML_Quick Form class, or many other validation classes widely available out there.

In order to obtain the domain part, we split the email address into the username and domain sections, respectively, using the PHP’s split() function, as listed below: Now, the $domain variable stores the corresponding domain.

Since we’re interested only in this, all we need to do is pass it in as a parameter for the PHP chekdnsrr() function to determine whether it’s a real domain.

It will look for the Mail Exchange record in the DNS (remember that the default type is MX), and return true if a MX record is found, which shows that the address displays a valid email domain.

If the function returns false, the email domain is not valid.

The first step to validating an email address is to check whether it is in the standard format.

Tags: , ,