Server side email validation in php with filter_var

Validating email address on server side is more secure way to prevent from span entry, Some people disabled javascript on their browser and enter wrong or garbage username/email address, So validating email on server side is good approach.
email-validation-php



You can use the filter_var() function, which gives you a lot of handy validation and more options.
Note: PHP 5.2.0 or higher is required for the filter_var function.

Here is the quick function in php to validate email address in single line.

function checkValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Above function will validate email like “iamrohitx@gmail” as a valid email, In Standard HTML5 email validation also pass this string too as a valid email, You need to add some extra security in your function to validate TLS so that you can get more filtered email data.

Email with TLS validation.

function checkValidEmail($email){ 
   return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email);
}

Example:

echo checkValidEmail('iamrohitx@gmail'); 
echo checkValidEmail('iamrohitx@gmail.'); 
echo checkValidEmail('[email protected]'); 
echo checkValidEmail('[email protected].'); // false



If you like this post please don’t forget to subscribe my public notebook for more useful stuff