PHP自带方法验证邮箱是否存在_php技巧

WBOY
Release: 2016-05-16 19:59:18
Original
1468 people have browsed it

PHP校验邮箱地址的方法很多, 比较常用的就是自己写正则了, 不过正则多麻烦, 我PHP自带了方法做校验。

filter_var

filter_var是PHP内置的一个变量过滤的方法, 提供了很多实用的过滤器, 可以用来校验整数、浮点数、邮箱、URL、MAC地址等。

filter_var如果返回false, 说明变量无法通过过滤器, 也就是不合法了。

$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));
Copy after login

输出:

string(21) "lastchiliarch@163.com" bool(false) string(7) 1@a.com
Copy after login

对于asb这种非法邮箱格式返回了false, 但对于1@a.com则通过了,还是略有瑕疵啊。

不过一般的正则也通过会认为1@a.com是一个合法的邮箱, 那有啥办法可以更精准的验证呢?

checkdnsrr

checkdnsrr其实是用来查询指定的主机的DNS记录的,我们可以借用它来验证邮箱是否存在。

对于1@a.com肯定是MX记录不存在的。

$email = "lastchiliarch@163.com"; var_dump(checkdnsrr(array_pop(explode("@",$email)),"MX")); $email = "1@a.com"; var_dump(checkdnsrr(array_pop(explode("@",$email)),"MX"));
Copy after login

输出:

bool(true) bool(false)
Copy after login

可以看到, 很完美, 唯一的缺点就是太慢了, 毕竟是要做一次网络请求。 所以不适合同步对大量的邮箱采用这种做法去校验。

filter_var+checkdnsrr

我们可以接合filter_var 和checkdnsrr做校验, 对于绝大多数的非法邮箱肯定会在filter_var的时候就挂掉了, 剩下的再用

checkdnsrr进一步判断。

$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; } }
Copy after login

输出:

invalid email: 1@a.com
Copy after login

但要注意的是, 由于只是检查MX记录, 所以只能判断163.com是存在的, 但不能说明lastchiliarch这个用户是存在的。

想要更精确的判断邮箱存在, 那只能连接到smtp服务器去验证了。

介绍了邮箱验证,PHP自带方法如何验证邮箱、URL、IP是否合法,下面为大家介绍:

主要还是使用的是filter_var函数

语法
filter_var(variable, filter, options)
variable 必需。规定要过滤的变量。
filter 可选。规定要使用的过滤器的 ID。
options 规定包含标志/选项的数组。检查每个过滤器可能的标志和选项。

PHP Filters

Example #1 A filter_var() example

<?php var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)); var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)); ?>
Copy after login

以上例程会输出:

string(15) "bob@example.com" bool(false)
Copy after login

以上就是本文的全部内容,希望对大家进行php邮箱验证有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!