Search This Blog

Sunday, October 02, 2011

PHP: Simple and Effective Way to Validate Email Addresses


There are a number of regular expression solutions that have been written to test the validity of user-entered email addresses in PHP, some of them quite good. However, the most consistent and reliable way to validate email addresses takes advantage of PHP's built-in functionality.

filter_var does just what it says: it filters a variable using a variety of pre-defined filters (see the complete list of filters categorized by type); when you are validating email addresses, the filter you want is FILTER_VALIDATE_EMAIL:
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
     exit('E-mail is not valid.');
}

1 comment: