HomePHP Page 4 - Building a PHP5 Form Processor: Coding the Form Validator Module
The big challenge: checking email addresses with the “validateEmail()” method - PHP
In this second part of a three-part series, we take up the topic of server-side validation. By the time you finish this article, you'll have the general guidelines for how to build a form validating class. You'll use some PHP built-in introspection functions, along with regular expressions, to assist you in building this class.
For anyone who has spent a long time writing validation routines, verifying email addresses is a challenging task. In the good old days, a robust email pattern coded in a regular expression was, most of the time, good enough to make sure that a user had entered a well-formed email address. Now, things are different, considering the vast number of current email domains. However, in order to keep the method’s source code simple and readable, I’ll walk through an intermediate example, and instruct the method to check only for well-formed addresses and existing domains in the DNS. Its signature is as follows:
As shown above, the method verifies whether the supplied email address is at least well-formed, without troubling things too much with complex patterns. It then searches in the DNS for the corresponding MX records, in order to determine whether the domain part corresponds to a real email domain. To perform this task, I use the “checkdnsrr()” PHP built-in function, which is extremely helpful when searching DNS records. Of course, this fact doesn’t mean that the user really exists, but it’s a decent way to check for the existence of a given email domain.
From this point onward, you can make your own way either by improving the effectiveness of this method or writing a full-fledged alternative solution, in order to verify user-supplied email addresses.
Now, in case you don’t know, the PHP “checkdnsrr()” function isn’t available on Windows systems, so here’s the alternative “windnsrr()”function, which essentially performs the same task on Microsoft servers:
After having defined the last checking method of the class, the only thing left to complete the definition of the form “validator” class consists of including two useful corollaries: the “checkErrors()” and “displayErrors()” methods.