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.
Within the huge and fascinating field of Web development, one of the most common tasks that many applications have to deal with is, undoubtedly, verifying whether a user email address is valid. Certainly, this should sound very familiar to most Web developers, whether they are setting up their first consciously-coded script or implementing full-blown applications required to handle more complex processes. Whatever the case, validating a visitor's email address to see if it belongs to a real domain is always a good step to help you avoid, at least partially, several possible problems that arise when applications are receiving incoming bogus data. From cluttering up databases with invalid information, to sending newsletters or similar content to email addresses at nonexistent domains, headaches are surely going to come up from receiving fake email.
Several approaches can be taken to address the problem, depending on the level of complexity desired for the validation itself. 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.
The third option involves writing our own set of functions for in-deep email address checking, which can be considered an intermediate solution between the two above described. This approach is versatile and portable enough to be used whether we want to expand basic validating functions or add extra functionality to existing classes.
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.