This guide provides a technical walkthrough for verifying email addresses with PHP. Included is a ready-to-implement PHP code snippet for email validation. Proceed to the implementation steps.

In discussing PHP Mail Validate in web development, you may also like to consider the importance of PHP header redirects.

Implementing Email Validation in PHP Using filter_var()

Explore the method of employing PHP’s filter_var() function for email address validation.

Consider a PHP variable designated to store an email address:

$email = “name@mydomain.com“;

  • To verify the validity of the $email variable as an email address, utilize the filter_var() function;
  • The filter_var() function in PHP is designed for variable validation and sanitization;
  • For email validation, specify the FILTER_VALIDATE_EMAIL flag within filter_var();
  • The function filter_var() will return true if the email address passes the validation, and false if it does not.

Usage example follows:

$email = 'name@mydomain.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
   
   echo $email . ' is a valid email address.';
}
else {
   
   echo $email . ' is NOT a valid email address.';
}

name@mydomain.com is a valid email address.

The filter_var() function discards email addresses lacking a proper “name@domain” structure or featuring disallowed characters in an email address.

Examples of permissible and impermissible addresses are provided below: 

$emails = [
   'name@mydomain.com',  // Valid address
   'name_with_\'_quotes@mydomain.com',  // Valid: single quotes are allowed
   '@mydomain.com',  // Not valid: missing name
   'name@',  // Not valid: missing domain
   'name with spaces@mydomain.com',  // Not valid: spaces are not allowed
   'name_with_"_doublequotes@mydomain.com', // Not valid: double quotes are not allowed
   'name1@name2@mydomain.com' // Not valid: too many "@"
];
foreach ($emails as $email) {
   
   echo $email . ' --> ';
   
   if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
      
      echo 'valid.<br>';
   }
   else {
      
      echo 'NOT valid.<br>';
   }
}

name@mydomain.com --> valid.
name_with_'_quotes@mydomain.com --> valid.
@mydomain.com --> NOT valid.
name@ --> NOT valid.
name with spaces@mydomain.com --> NOT valid.
name_with_"_doublequotes@mydomain.com --> NOT valid.
name1@name2@mydomain.com --> NOT valid.

Comparison Between Validation and Sanitization

man sit at the table, clicking the mouse and watching on the computer screen with @ on it

The filter_var() function can utilize the FILTER_SANITIZE_EMAIL flag for sanitizing email addresses. This process involves eliminating characters that are not permissible in an email address. However, this method does not ensure the validity of the email address; it merely removes inappropriate characters. A string, even after sanitization, might not conform to the required email address format. Consider the following example for clarity:

$address = 'invalid_address_£()@';
echo 'Address: ' . $address . '<br>';
/* Sanitization removes all the invalid characters... */
$sanitizedAddress = filter_var($address, FILTER_SANITIZE_EMAIL);
echo 'Sanitized address: ' . $sanitizedAddress . '<br>';
/* However, the address is still invalid. */
if (filter_var($sanitizedAddress, FILTER_VALIDATE_EMAIL)) {
  
   echo 'The address is valid.';
}
else {
  
   echo 'The address is still not valid.';
}

Address: invalid_address_£()@
Sanitized address: invalid_address_@
The address is still not valid.

Using the FILTER_SANITIZE_EMAIL flag isn’t very helpful because you’ll still have to validate the variable. It’s better to just use the FILTER_VALIDATE_EMAIL flag instead.

Verifying the Domain of an Email Address

Upon confirming the syntactical correctness of your email address, the next step involves ascertaining the actual existence of the email address in question.

The definitive method entails dispatching an email to the address and scrutinizing the response from the SMTP server. Nevertheless, this approach presents complexities and lacks consistent reliability.

A more straightforward and feasible alternative is to examine the domain component of the email address. Establishing the legitimacy of the domain offers a reasonable basis to infer the validity of the email address.

The initial phase in this process involves isolating the domain from the email address. The procedure for domain extraction is as follows:

$address = 'myaddress@gmail.com';
// Find the position of @
$atPos = mb_strpos($address, '@');
// Select the domain
$domain = mb_substr($address, $atPos + 1);

Next, utilize the checkdnsrr() function to authenticate the domain.

This function requires two parameters. The first is the domain, appended with a period to prevent inaccurate searches. The second parameter is the string “MX”, instructing the function to probe for the Mail Exchange (MX) DNS record.

The corresponding code snippet is as follows:

if (checkdnsrr($domain . '.', 'MX')) {
   
   echo 'Domain "' . $domain . '" is valid';
}
else {
   
   echo 'Domain "' . $domain . '" is not valid';
}

Domain “gmail.com” is valid

Implementing Email Validation on the Front-End

Email validation at the front-end level is executed within the browser environment.

For instance, designating the attribute of an HTML form input as “email” triggers the browser’s innate mechanism to block the submission of syntactically incorrect email addresses:

Email: <input type=”email”>

Additionally, JavaScript can be employed to conduct further validation processes.

While front-end validation serves to intercept common user errors and enhance the overall user experience, its security robustness is limited. It’s crucial to acknowledge that front-end validation can be circumvented by malevolent entities, enabling the submission of invalid data to the server-side PHP script.

Therefore, it is imperative to conduct a thorough validation using PHP on the server side to ensure data integrity and security.

PHP Email Validation Example

an opened laptop with email word on it, a flowers and notebooks on the table

Presented here is a detailed PHP email validation example, intended as a template for your coding endeavors.

The process initiates with an HTML form, featuring an email input field designated as “email”:

<form>
Your email: <input type="email" name="email">
<input type="submit" value="Submit">
</form>

Subsequent to the HTML form, we delve into the PHP segment for email validation:

$email = NULL;
/* Read the "email" request variable. */
if (isset($_REQUEST['email'])) {
   
   $email = $_REQUEST['email'];
}
/* Validate the address. */
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
   
   echo $email . ' is NOT a valid email address.';
   die();
}
/* Check the domain. */
$atPos = mb_strpos($email, '@');
$domain = mb_substr($email, $atPos + 1);
if (!checkdnsrr($domain . '.', 'MX')) {
   
   echo 'Domain "' . $domain . '" is not valid';
   die();
}
/* The address is valid. */
echo $email . ' is a valid email address.';

Conclusion

To summarize the key points of the tutorial, email address validation can be effectively achieved using the filter_var() function with the FILTER_VALIDATE_EMAIL flag. Alternatively, employing the FILTER_SANITIZE_EMAIL flag with filter_var() leads to the removal of invalid characters from the email string, though this does not confirm the email address’s validity. Additionally, the validity of a domain can be assessed using the checkdnsrr() function. It’s important to note that front-end validation, while useful, lacks security robustness. Hence, implementing PHP-based validation on the server side is essential for ensuring data integrity and security.

Leave a Reply

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