Php accurately checks whether the email address has a background
PHP provides many methods to verify the email address. it is commonly used to write regular expressions by yourself. However, regular expressions are much more troublesome. I have provided PHP methods for verification.
Filter_var
Filter_var is a built-in variable filtering method in PHP. It provides many practical filters that can be used to verify integers, floating point numbers, mailboxes, URLs, and MAC addresses.
For more information about filters, see filters. validate.
Filter_var if false is returned, the variable cannot pass the filter, that is, it is invalid.
$ Email = "lastchiliarch@163.com"; var_dump (filter_var ($ email, FILTER_VALIDATE_EMAIL); $ email = "asb"; var_dump (filter_var ($ email, FILTER_VALIDATE_EMAIL )); $ email = "1@a.com"; var_dump (filter_var ($ email, FILTER_VALIDATE_EMAIL); output: string (21) "lastchiliarch@163.com" bool (false) string (7) "1@a.com"
False is returned for an invalid email address format such as asb, but it is still slightly defective if the 1@a.com passes.
But the general regular also through will think 1@a.com is a legitimate mailbox, then what method can be more accurate verification?
Checkdnsrr
Checkdnsrr is actually used to query the DNS records of the specified host. we can use it to verify whether the mailbox exists.
The MX record does not exist for 1@a.com.
$ Email = "lastchiliarch@163.com"; var_dump (checkdnsrr (array_pop (explode ("@", $ email), "MX"); $ email = "1@a.com "; var_dump (checkdnsrr (array_pop (explode ("@", $ email), "MX"); output: bool (true) bool (false)
We can see that it is perfect. The only drawback is that it is too slow. after all, it is a network request. Therefore, it is not suitable for synchronous verification of a large number of mailboxes.
Filter_var + checkdnsrr
We can check filter_var and checkdnsrr. for most illegal emails, the filter_var will be suspended, and the rest will be reused.
Checkdnsrr further judgment.
$ Email_arr = array ("lastchiliarch@163.com", "1@a.com"); foreach ($ email_arr as $ email) {if (filter_var ($ email) = false) {echo "invalid email: $ email \ n"; continue;} if (checkdnsrr (array_pop (explode ("@", $ email), "MX ") = false) {echo "invalid email: $ email \ n"; continue;} output: invalid email: 1@a.com
However, it should be noted that, because we only check MX records, we can only judge that 163.com exists, but it cannot be said that the user lastchiliarch exists.
To determine the existence of a mailbox more accurately, you can only connect to the smtp server for verification.