Check if a string is an email address in PHP
I am trying to do an SQL query, but I need to check somehow if the value is an email address.
I need a way to check if $user
is an email address, because I have user values such as this in my table.
test
test2
[email protected]
[email protected]
test392
[email protected]
and so on...
I need to make it so $useremail
checks $user
to find if it's an email address. So I can UPDATE the values, WHERE user=test OR [email protected]
, etc.
$user = strtolower($olduser);
$useremail = "";
mysql_query("UPDATE _$setprofile SET user=$sn, fc=$fc WHERE user='$user' OR user='$useremail");
Without regular expressions:
<?php
if(filter_var("[email protected]", FILTER_VALIDATE_EMAIL)) {
// valid address
}
else {
// invalid address
}
?>
This is not a great method and doesn't check if the email exists but it checks if it looks like an email with the @ and domain extension.
function checkEmail($email) {
$find1 = strpos($email, '@');
$find2 = strpos($email, '.');
return ($find1 !== false && $find2 !== false && $find2 > $find1);
}
$email = '[email protected]';
if ( checkEmail($email) ) {
echo $email . ' looks like a valid email address.';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo 'This is a valid email address.';
echo filter_var($email, FILTER_VALIDATE_EMAIL);
//exit("E-mail is not valid");
}
else
{
echo 'Invalid email address.';
}