How to validate email address in PHP?

I am learning PHP and currently working on user registration. In the registration process, I am trying to validate the email address field. When a user submits a registration form, I want to check the the email he provided is a valid email and not just random string looks like email. The problem is I am not sure how to check if the email address is valid. Can anyone show me the best way to check an email address in PHP?

You can use the filter_var function to check if an email address is valid. The filter_var function takes two arguments: the value to validate and the validation filter.

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

The FILTER_VALIDATE_EMAIL filter checks whether the given value is a valid email address. If the email address is valid, the function will return true. Otherwise, it will return false.

You can also use regular expressions to check if an email address is valid.

if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
    // Email address is valid
}

It’s important to note that this validation method can only check the syntax of the email address. It doesn’t check if the email address actually exists.

Additionally, you can also check whether the domain defines an MX record.

if (checkdnsrr($domain, 'MX')) {
    // Domain is valid
}