Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Validating Email Addresses in PHP

DZone's Guide to

Validating Email Addresses in PHP

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

A very quick snippet today because I've told two people to use this approach in the last few days and both of them told me they didn't know about it. How to check if an email address is valid in PHP: use one of the Filter functions, like this:

$email1 = "nonsense.something@dottiness";  // not a valid email
$email2 = "dotty@something.whatever";  // valid email
 
$clean_email1 = filter_var($email1, FILTER_VALIDATE_EMAIL); // $clean_email1 = false
$clean_email2 = filter_var($email2, FILTER_VALIDATE_EMAIL); // $clean_email2 = dotty@something.whatever

The Filter extension was new in PHP 5.2, but is one of the unsung heroes of the language. It's rare for me to ever describe one approach as the "right" way to do something - but for validating data, Filter really is excellent, offering both validating and sanitising filters and generally making it super-easy to clean up incoming variables. Many of the frameworks offer equivalents, and I'm sure many of those are wrapping this too.

 

 

 

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}