Phi*_*hil 16 php email dns validation
我需要为一个我正在努力工作的项目编写一个函数,我们正在创建一个只能由机构的学生,员工和校友访问的网站.
我们说学校的网站是:school.edu.
我在编写一个php过滤器时遇到问题,该过滤器检查提交的电子邮件地址是否为"school.edu"域
我将用一个例子.Dude#1的电子邮件是user@mail.com,而Dude#2的电子邮件是user@school.edu.我想确保Dude 1收到错误消息,而Dude#2成功注册.
这就是我要做的事情的要点.在不久的将来,该网站将允许另外两个地区学校注册:school2.edu和school3.edu.然后我需要检查器根据域名的小列表(可能是数组?)检查电子邮件,以验证电子邮件是否在列表中是域名.
Wes*_*rch 33
有几种方法可以实现这一点,这里有一个:
// Make sure we have input
// Remove extra white space if we do
$email = isset($_POST['email']) ? trim($_POST['email']) : null;
// List of allowed domains
$allowed = [
'school.edu',
'school2.edu',
'school3.edu'
];
// Make sure the address is valid
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
// Separate string by @ characters (there should be only one)
$parts = explode('@', $email);
// Remove and return the last part, which should be the domain
$domain = array_pop($parts);
// Check if the domain is in our list
if ( ! in_array($domain, $allowed))
{
// Not allowed
}
}
Run Code Online (Sandbox Code Playgroud)
你可以使用正则表达式:
if(preg_match('/^\w+@school\.edu$/i', $source_string) > 0)
//valid
Run Code Online (Sandbox Code Playgroud)
现在继续在评论中撕裂我,因为有一些疯狂的电子邮件地址功能,我没有考虑:)
请注意,由于电子邮件地址(如user@students.ecu.edu),在@之后获取所有内容可能无法实现您要完成的任务.下面的get_domain函数只会将域下移到第二级域.它将返回username@unc.edu或username@mail.unc.edu的"unc.edu". 此外,您可能希望考虑具有国家/地区代码的域(其中包含2个字符的顶级域名).
您可以使用以下函数来提取域.然后,您可以使用一系列学校域名,或将学校域名放入数据库并检查电子邮件地址.
function get_domain($email)
{
if (strrpos($email, '.') == strlen($email) - 3)
$num_parts = 3;
else
$num_parts = 2;
$domain = implode('.',
array_slice( preg_split("/(\.|@)/", $email), - $num_parts)
);
return strtolower($domain);
}
// test the function
$school_domains = array('unc.edu', 'ecu.edu');
$email = 'someone@students.ecu.edu';
if (in_array(get_domain($email), $school_domains))
{
echo "good";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24325 次 |
| 最近记录: |