- PHP

How to check if e-mail is valid in PHP

Use filter_var() function with FILTER_VALIDATE_EMAIL.

Remember, this checks only if the e-mail format is valid, not if the e-mail address exists.

<?php

if (!filter_var('[email protected]', FILTER_VALIDATE_EMAIL) === false) {
    // do this if e-mail is valid
} else {
    // or this if is not
}

?>

Example:

<?php

$email = '[email protected]';

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    echo 'E-mail is valid';
} else {
    echo 'E-mail is not valid';
}

?>

Output: E-mail is valid

PHP is e-mail function

If you need to validate e-mail addresses multiple times in your code, you can use a function, like this one:

<?php

function isEmail($email) {
  if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    return true;
  } else {
    return false;
  }
}

?>

Example:

<?php

function isEmail($email) {
  if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    return true;
  } else {
    return false;
  }
}

if(isEmail('hello')) {
  echo 'Valid e-mail';
} else {
  echo 'Invalid e-mail';
}

?>

Output: Invalid e-mail