4

If I'm allowing a user to enter an email address to be saved into the database, should I use is_email() or sanitize_email()?

Ex.

update_user_meta( $user_id, $social_site, sanitize_email( $_POST[$user_input] ) );
  • Please, add solution as answer and mark it as accepted. (Yes, you can answer your own questions). In this way you'll help people to understand which questions have a solution and which not. Your Question is seen as "unanswered" by users and in site statistics tool. – gmazzap Sep 15 '14 at 23:08
6

is_email() will take the provided string( a email address) and run checks on it to ensure that it is indeed an email address and that the string has no illegal characters in it. It would simply not change anything in the string you provided but return either true if the string passes all the function checks or false if it doesn't.

The sanitize_email() will take the provided string and strip out any characters that are not allowed in an email address and return only the characters that are allowed.

So if you had a string that needs to be an email like: user"!@provider.com

is_email() would return false as the string contains characters that are not allowed in an email address.

sanitize_email() would return user!@provider.com

If you take user"!@provider.com and first run it through the sanitize_email() function and then through the is_email() function it would then return true in this case as all the invalid characters are removed from the string and this allows the string to pass the is_email() checks.

I would suggest using both, is_email() to check first if the user submitted a proper email address and before commiting anything into the database check that is is indeed safe by running the sanitize_email() function at the latest possible point in your script.

  • thanks for the clarification. I've just updated my answer with the proposed solution. Can you verify that this is the correct approach? – user54141 Sep 15 '14 at 21:20
  • Check out this page for some nifty info on the topic: code.tutsplus.com/tutorials/…. One should check that the data is what it is expected to be and that it is valid as soon as it comes from the user. Data should be sanitized when we use it. But in this situation saving an email address that is invalid to the database after it has been sanitized would not be useful to me or the user. One would still have to escape the address on output though, but making sure that it is valid and the expected format cant hurt. – Waylon Fourie Sep 15 '14 at 22:02
  • Ok I see now. Validate input right away, sanitize right before output. – user54141 Sep 16 '14 at 0:32
  • is_email returns the valid email address it does not return TRUE. – Jason May 23 '16 at 5:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.