PHP email validation

27,168

Solution 1

I suggest you use the FILTER_VALIDATE_EMAIL filter:

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //valid
}

You can also use its regular expression directly:

"/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD"

But in that case, if a bug is found in the regular expression, you'll have to update your program instead of just updating PHP.

Solution 2

Unless you want to use a very very long regular expressions you'll run into valid email addresses that are not covered (think Unicode). Also fake email addresses will pass as valid, so what is the point of validating if you can simply write [email protected] and get away with it?

The best way to validate email addresses is to send a confirmation email with a link to click. This will only work if the email address is valid: easy, and no need to use regex.

Share:
27,168
Mark Lalor
Author by

Mark Lalor

I began my programming journey at the age of 11. My 5th grade teacher showed me that I could save a file on notepad with another file extension than .txt! Thus began my interest in HTML, CSS, Javascript, PHP, PHP GD, jQuery, SQL, C#, .NET Framework, C, C++, mobile apps, DragonFireSDK (7/10 would not use again), Objective C, and Java, in that order. I learned only through books and the internet, which is why I asked many dumb questions years ago. I like to look back on them and reminisce on my bad programming skills and problem-solving.

Updated on July 06, 2020

Comments

  • Mark Lalor
    Mark Lalor almost 4 years

    For PHP what is the best email validation using preg, NOT ereg because it's deprecated/removed.

    I don't need to check if the website exists (it's not like maximum security).

    I've found many ways with ereg but they (obviously) aren't good practice.