Validating email addresses more easily in PHP
For years when I was validating email addresses on forms on old PHP websites, I would always use a regular expression stolen from the internet and preg_match() to validate the email string against the regular expression, which has served me well for many years - until today when I got a bug report from a client where one of their clients was using an email address with a subdomain e.g: firstname.lastname@example.org, which ultimately failed against the regex.
After a bit of Googling, I realised the regex wasn't following the RFC 2822 standard (which I also found today!). There was plenty of regex rules out there which followed this standard, however they were extremely long. After more hunting around on Google, a user suggested on a forum post to use filter_var() - which has turned out to be a hidden gem
It made the whole process a lot more simpler, here's an example of how to use:
$email = filter_var($email, FILTER_VALIDATE_EMAIL));
Simple as that! The filter_var() function will return the email address if valid and false if invalid, pretty cool ah? Also the filter_var() can be used to filter URLs, IP addresses and data types. A full list can be found here: http://www.php.net/manual/en/filter.filters.validate.php.
Posted: Tue, Jun 14th 2011, 19:14
Leave a comment
To leave a comment please fill out the form below.
There are no comments for this post.
- June 2011 (2)