77

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
test@example.com
test2@example.com
test392
test@example.net

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 user=test@example.com, etc.

$user = strtolower($olduser);
$useremail = "";

mysql_query("UPDATE _$setprofile SET user=$sn, fc=$fc WHERE user='$user' OR user='$useremail");
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
homework
  • 4,987
  • 11
  • 40
  • 50
  • 2
    Why does it matter if a value is an email address? A string can be a perfectly formatted email address and still not be valid, like `StackOverflowIsAGreatWebsite@whitehouse.gov`. So the only way to know for sure if an address is valid is to try to send mail to it. And if you're not going to send mail to it, why do you care? – Daniel Pryden Nov 12 '09 at 23:23
  • @Daniel Pryden I have stored usernames in my database. I want to update the email values to regular values, so when I run my script, it pulls the username data from the API, and then I can replace the old email value, with the new username value. It's more convenient for the script I am trying to write. – homework Nov 13 '09 at 00:06

11 Answers11

277

Without regular expressions:

<?php
    if(filter_var("some@address.com", FILTER_VALIDATE_EMAIL)) {
        // valid address
    }
    else {
        // invalid address
    }
?>
Uri
  • 2,771
  • 2
  • 15
  • 2
  • 11
    Top tip! NB this is PHP v5.2.0 or greater only – richsage Nov 12 '09 at 22:49
  • 1
    @richsage: Right, the `filter` extension has been enabled by default since PHP 5.2.0 (released 2006-11-02). For earlier PHP versions, you could download and install the filter extension from PECL. – Bill Karwin Nov 12 '09 at 22:59
  • 3
    This allows for `somename@somedomain`, without a domain extension such as .com. Is there a way to fix this? – Mike Moore Jun 05 '10 at 16:48
  • @MikeMoore -- there are legal (though rare) addresses in top-level domains, so it would actually be incorrect to require a dot in the domain name. – TextGeek May 03 '16 at 15:25
  • 1
    @MikeMoore from http://php.net/manual/en/filter.filters.validate.php "In general, this validates e-mail addresses against the syntax in RFC 822, with the exceptions that comments and whitespace folding and ***dotless domain names are not supported***." – Erics Apr 06 '17 at 05:57
18
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.';
} 
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Ben
  • 189
  • 1
  • 4
11

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 = 'name@email.com';
if ( checkEmail($email) ) {
   echo $email . ' looks like a valid email address.';
}
TURTLE
  • 3,728
  • 4
  • 49
  • 50
  • 3
    `email@com` is a valid email address: http://en.wikipedia.org/wiki/Email_address#Valid_email_addresses – Toto Dec 16 '13 at 19:29
  • `user.name@gmail.com` is invalid, that's not working – Mohsen Safari Apr 18 '19 at 14:14
  • @MohsenSafari Just take out the && $find2 > $find1 part in the return and it will just check if it has an @ and . – g4ost Jun 04 '19 at 19:25
  • dont use this, it simply fails if there's a `.` before `@` as its comparing the position of `@` and `.` would fail on something like `my.name@gmail.com` which is a valid email – SymmetricsWeb Sep 16 '22 at 02:22
8

The simplest approach is to use a regular expression to check email addresses, although there's some disagreement about how accurate this can be. This process is discussed in detail here:

Using a regular expression to validate an email address

You can use REGEXP in MySQL to select from the database based on your regular expression:

http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Community
  • 1
  • 1
Travis
  • 4,018
  • 4
  • 37
  • 52
6

This function is_email() will give you an definite answer to whether the string is a valid email address or not. As far as I know, no other solution will do this with the same level of authority.

If I understand the example correctly, you would use it like this

$user = strtolower($olduser);
$useremail = (is_email($user)) ? $user : '';

The PHP built-in function is incomplete. I'm the principle author of is_email() so I'm blowing my own trumpet here, but I've put a lot of work into this in order that nobody else should have to ever again.

Denilson Sá Maia
  • 47,466
  • 33
  • 109
  • 111
Dominic Sayers
  • 1,783
  • 2
  • 20
  • 26
5

You can use regular expressions to validate your input string to see if it matches an email address:

<?php 
$email = "someone@example.com"; 
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) { 
  echo "Valid email address."; 
} 
else { 
  echo "Invalid email address."; 
} 
?>

From: http://www.totallyphp.co.uk/code/validate_an_email_address_using_regular_expressions.htm

EDIT: for more accurate expressions, please refer to Travis answer on this question

Community
  • 1
  • 1
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
3

I've been using this function for many years across hundreds of sites. It's probably not perfect, but i've never had a complaint of false negatives (or positives):

function validate_email($email) {
    return (preg_match("/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/", $email) || !preg_match("/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/", $email)) ? false : true;
}
Rob
  • 8,042
  • 3
  • 35
  • 37
3

Apart from all regex suggestions which mostly doesn't support all of the available TLD's (including for example .info and .museum) and the upcoming ICANN decision to allow Chinese and Arabic in URL's (which would let [a-z] and \w fail) for which the following more generic regex is sufficient

([^.@]+)(\.[^.@]+)*@([^.@]+\.)+([^.@]+)

I would also mention that doing a WHERE user=test OR user=test@example.com is too error prone. Better use an autogenerated PK in the table and use it in the WHERE clause.

I don't really see the value of strict, long and unreadable mailregexes conforming the RFCxxxx specs. Best way is still to send a mail with a link with an activation key to the end user to let it confirm the mail address. Inform that in the form as well. If necessary let the user type the email address twice like you do for passwords.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
3

Since everybody is posting their regular expression, here's mine: ^((([\w+-]+)(.[\w+-]+)*)|(\"[^(\|\")]{0,62}\"))@(([a-zA-Z0-9-]+.)+([a-zA-Z0-9]{2,})|[?([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})(.([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})){3}]?)$

To the best of my knowledge, it supports everything in the RFC specification, including a lot of things that most people don't usually include.

Scott
  • 6,411
  • 6
  • 39
  • 43
2
$email = "email@string.com";

function isEmail($email) {
     if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
          return true
     } else {
          return false
     }
}

if (isEmail($user_email)) {
     // email is valid, run the query
     mysql_query("UPDATE _$setprofile SET user=$sn, fc=$fc WHERE user='$user' OR user='$user_email");
}
Jerry Abraham
  • 1,039
  • 18
  • 42
iamkoa
  • 2,217
  • 6
  • 21
  • 21
0
$user_email = "email@gmailcom";

function isEmail($email) {
     if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
          return true;
     } else {
          return false;
     }
}

if (isEmail($user_email)) {
     // email is ok!
} else {
     // email not ok
}