{"id":127472,"date":"2022-08-22T14:52:10","date_gmt":"2022-08-22T14:52:10","guid":{"rendered":"https:\/\/phppot.com\/?p=19045"},"modified":"2022-08-22T14:52:10","modified_gmt":"2022-08-22T14:52:10","slug":"php-validate-email-using-filter_validate_email-and-regex","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/08\/22\/php-validate-email-using-filter_validate_email-and-regex\/","title":{"rendered":"PHP Validate Email using filter_validate_email and regex"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1111111111111\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on August 22nd, 2022.<\/div>\n<p>Email validation in PHP can be done in different ways. In general, a website will have <a href=\"https:\/\/phppot.com\/jquery\/jquery-form-validation-with-tooltip\/\">client-side validation<\/a>.<\/p>\n<p>I prefer both client and <a href=\"https:\/\/phppot.com\/php\/php-form-validation\/\">server-side validation<\/a>. It is applicable not only for emails but also to all inputs received from the end users. It will make the website more robust.<\/p>\n<p>Validating email or other user inputs is a basic precautionary step before processing.<\/p>\n<p>In this article, we will see how to validate email on the server-side. PHP provides various alternates to validate email with its built-in constants and functions. Some of them are listed below.<\/p>\n<h2>Ways to validate email in PHP<\/h2>\n<ol>\n<li>Using FILTER_VALIDATE_EMAIL.<\/li>\n<li>Using pattern matching with regular expression.<\/li>\n<li>By validating the domain name from the email address.<\/li>\n<\/ol>\n<p>The following quick example uses <a href=\"https:\/\/www.php.net\/manual\/en\/filter.filters.validate.php\" target=\"_blank\" rel=\"noopener\">PHP filter<\/a> FILTER_VALIDATE_EMAIL. It is the <strong>best method of validating email in PHP<\/strong>.<\/p>\n<div class=\"post-section-highlight\" readability=\"35\">\n<h2>Quick example<\/h2>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php\n$email = 'test@example.com';\nisValidEmail($email); \/\/ using FILTER_VALIDATE_EMAIL - this is the best option to use in PHP\nfunction isValidEmail($email)\n{ return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;\n}\n?&gt;\n<\/code><\/pre>\n<\/div>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-19057\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-validate-email-550x432.jpg\" alt=\"php validate email\" width=\"550\" height=\"432\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-validate-email-550x432.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-validate-email-300x235.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-validate-email-768x603.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2022\/08\/php-validate-email.jpg 803w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<p>Let us see other methods to validate email using PHP script.<\/p>\n<h2>Using FILTER_SANITIZE_EMAIL for input sanitization<\/h2>\n<p>The FILTER_SANITIZE_EMAIL is used to clean the email data submitted by the user.<\/p>\n<p>In this example, the $email is hard coded with an example email address. You can supply email input from the form data posted to PHP using <a href=\"https:\/\/phppot.com\/php\/php-request-methods\/\">GET or POST methods<\/a>.<\/p>\n<p>It adds a prior step to sanitize the email data before validating its format. For validating the format of the sanitized email data, it uses FILTER_VALIDATE_EMAIL.<\/p>\n<p class=\"code-heading\">filter-sanitize-email.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php\n\/\/ this script explains the difference between FILTER_SANITIZE_EMAIL and FILTER_VALIDATE_EMAIL \/\/ validation is to test if an email is in valid email format and FILTER_VALIDATE_EMAIL should be used.\n\/\/ sanitization is to clean an user input before using it in the program and FILTER_SANITIZE_EMAIL should be used.\n$email = \"test@example.com\";\n$cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL); \/\/ after sanitization use the email and check for valid email or not\nif (filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)) { \/\/ the email is valid and use it\n}\n?&gt;\n<\/code><\/pre>\n<h2>Using pattern matching with regular expression<\/h2>\n<p>If you are expecting a regex pattern to validate the email format, this example code will help.<\/p>\n<p>This code has a regex pattern in a variable and is used to validate email with PHP preg_match().<\/p>\n<p>In PHP, the preg_match() is for pattern matching with a given subject that is an email address here.<\/p>\n<p>This code has the validateWithRegex() function to process the PHP email validation. It applies converts the input email string to lower case and trims before applying preg_match().<\/p>\n<p>Then, it returns a boolean true if the match is found for the email regex pattern.<\/p>\n<p class=\"code-heading\">email-regex.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php\nvalidateWithRegex($email); \/\/ Using regular expression (regex). If for some reason you want to validate email via a regex use this\n\/\/ function. The best way to validate is via FILTER_VALIDATE_EMAIL only.\nfunction validateWithRegex($email)\n{ $email = trim(strtolower($email)); \/\/ the regex I have used is from PHP version 8.1.7 which is used in php_filter_validate_email \/\/ reference: https:\/\/github.com\/php\/php-src\/blob\/PHP-8.1.7\/ext\/filter\/logical_filters.c#L682 $emailRegex = '\/^(?!(?:(?:\\\\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\\\\pL\\\\pN]+)|(?:\\\\x22(?:[\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7F\\\\pL\\\\pN]|(?:\\\\x5C[\\\\x00-\\\\x7F]))*\\\\x22))(?:\\\\.(?:(?:[\\\\x21\\\\x23-\\\\x27\\\\x2A\\\\x2B\\\\x2D\\\\x2F-\\\\x39\\\\x3D\\\\x3F\\\\x5E-\\\\x7E\\\\pL\\\\pN]+)|(?:\\\\x22(?:[\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7F\\\\pL\\\\pN]|(?:\\\\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}))\\\\]))$\/iDu'; if (preg_match($emailRegex, $email) === 1) { return true; } else { return false; }\n}\n?&gt;\n<\/code><\/pre>\n<h2>By validating the domain name from the email string<\/h2>\n<p>This method is a very simple one for validating email. It validates email by ensuring its host DNS validness.<\/p>\n<p>It uses the PHP checkdnsrr() function to validate DNS by a hostname or the <a href=\"https:\/\/phppot.com\/php\/how-to-get-the-client-user-ip-address-in-php\/\">site IP address<\/a>.<\/p>\n<p>This function returns a boolean true if the host has any DNS records found. And thereby, the email in that host can be considered in a valid format.<\/p>\n<p>It follows the below list of steps.<\/p>\n<ol>\n<li>It extracts the domain name from the email.<\/li>\n<li>It extracts the username prefixed before the @ symbol.<\/li>\n<li>It ensures that the username and domain name are not empty.<\/li>\n<li>It checks if the DNS details are not empty about the host extracted from the input email.<\/li>\n<\/ol>\n<p class=\"code-heading\">domain-validate-email.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php \/\/ simplest custom email validation using email's domain validation\nfunction validateEmail($email)\n{ $isEmailValid = FALSE; if (! empty($email)) { $domain = ltrim(stristr($email, '@'), '@') . '.'; $user = stristr($email, '@', TRUE); \/\/ validate email's domain using DNS if (! empty($user) &amp;&amp; ! empty($domain) &amp;&amp; checkdnsrr($domain)) { $isEmailValid = TRUE; } } return $isEmailValid;\n}\n?&gt;\n<\/code><\/pre>\n<p><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/php\/php-validate-email.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/php\/php-validate-email\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on August 22nd, 2022. Email validation in PHP can be done in different ways. In general, a website will have client-side validation. I prefer both client and server-side validation. It is applicable not only for emails but also to all inputs received from the end users. It will make the website [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":127473,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-127472","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127472","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=127472"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127472\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/127473"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=127472"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=127472"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=127472"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}