Checking for valid email address in PHP

Sooner or later, you are going to have a form that you are asking your website visitor to fill out. On that form you’ll be asking for an email address and you want to make sure it is valid. Until now might have used a PHP function containing the ereg call something like:

if(ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]
+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $mail)) {
      return true;
    } else {
      return false;

But, with PHP 5.3 the ereg function has been deprecated. So how do you test for a valid email? It’s really simple! From PHP 5.2 there has been a function filter_var/Filter_Valid_Email:

function CheckEmail( $email ){
    return filter_var( $email, FILTER_VALIDATE_EMAIL );

This little snippet of code will validate the variable ($email) and return if it is, or is not a valid email.

About Michael Coles

Michael Coles is the managing director of Cowan Creek Consulting. He holds an MBA from Macquarie University and a BSc from the University of Westminster.
This entry was posted in PHP & HTML. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>