• Feed RSS

Quick Tip: Validate Email Addresses with PHP

Quick Tip: Validate Email Addresses with PHP: "
Email validation is a common task that most developers have to deal with on a regular basis. Far too often the complex approach is taken (regular expressions), when PHP 5 has a super simple way to validate / sanitize your email string.



Filtering Variables the PHP 5 Way


So what is the quick method to validating emails? The function called filter_var(). This function allows you to run your variable through a filter that you specify, and can either validate the variable, or return a sanitized string depending on the filter you choose.

What does this look like…

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php

//Bad Email...

$badEmail = "bad@email";



//Run the email through an email validation filter.

if( !filter_var($badEmail, FILTER_VALIDATE_EMAIL) ){

echo "Email is no good.";

}else{

echo "Nice email.";

}



//Result - Email is no good.

?>

Alternatively you can use the sanitize filter, and it will remove any characters that aren’t valid.

1
2
3
4
5
6
7
8
9
<?php

//Crappy email.

$var="bad%%@em\#ail.com";



//Runs email through a sanitize filter

print filter_var($var, FILTER_SANITIZE_EMAIL);



//Result - bad@email.com

?>

As you can see these are super easy. You no longer have to worry about your regular expressions sucking. Php has you covered."