Validate email address in PHP

Discuss coding issues, and scripts related to PHP and MySQL.
MarPlo
Posts:186

Validate email address in PHP

What is the best way to validate an email address in PHP?
I currently use preg_match() with a RegExp:

Code: Select all

$email = 'some_name@domain.com';
if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/', $email)) {
  echo 'valid email';
}
else {
  echo 'not valid email';
} 
Is there a better /simpler method?

Admin Posts:805
The easiest and safest way to check whether an email address is well-formed is to use the filter_var() function:

Code: Select all

$email = 'some_name@domain.com';
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo 'valid email';
}
else {
  echo 'not valid email';
}

Similar Topics