我需要为我正在努力工作的项目编写一个函数,我们正在制作一个网站,只有学生,工作人员和校友才能访问。
让我们说学校的网站是:school.edu。
我在编写一个php过滤器时遇到问题,该过滤器检查提交的电子邮件地址是否具有“school.edu”域名
我会用一个例子。 Dude#1的电子邮件是user@mail.com,而Dude#2的电子邮件是user@school.edu。我想确保Dude 1收到错误消息,而Dude#2成功注册。
这就是我想要做的事情的要点。在不久的将来,该网站将允许另外两个地区学校注册:school2.edu和school3.edu。然后我需要检查器根据域名的小列表(可能是数组?)检查电子邮件,以验证该电子邮件是否在列表中是域名。
答案 0 :(得分: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
}
}
答案 1 :(得分:6)
您可以使用正则表达式:
if(preg_match('/^\w+@school\.edu$/i', $source_string) > 0)
//valid
现在继续在评论中撕开我,因为我没有考虑到一些疯狂的电子邮件地址功能:)
答案 2 :(得分:5)
请注意,由于电子邮件地址(如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";
}
答案 3 :(得分:3)
我只是这样做:
$acceptedDomains = array('site1.edu', 'site2.edu');
if(in_array(substr($email, strrpos($email, '@') + 1), $acceptedDomains))
{
// Email is from a domain in $acceptedDomains
}
'whatever.edu'部分将始终位于@
之后。所以,你需要做的就是:
@
。 (在普通电子邮件中,只有 一个,但这并不重要。)@
之后获取电子邮件的部分内容。这将是域名。in_array()
将域名与$acceptedDomains
中接受域名列表进行比较。请注意,如果您还要接受来自email@any.subdomain.site1.edu
的电子邮件,则必须执行更多操作,但这可能适用于此处,也可能不适用。我还假设您已经确认电子邮件地址已经完成,然后再进行此操作。
答案 4 :(得分:3)
简单和单行:
list($name, $domain) = explode('@', $email);
答案 5 :(得分:1)
您可以随时执行以下操作:
$good_domains = array('school.edu'); //in the future, just add to this array for more schools
$email = "user@school.edu"; //your user's email
$matches = array();
preg_match("/^(.+)@([^\(\);:,<>]+\.[a-zA-Z]{2,4})/", $email, &$matches); //validates the email and gathers information about it simultaneously
//should return ['user@mail.com', 'user', 'mail.com']
$domain = $matches[3];
if(in_array($domain, $goood_domains))
{
//success! your user is from school.edu!
}
else
{
//oh no! an imposter!
}
答案 6 :(得分:1)
如果您使用的是Laravel:
Str::endsWith($email, '@foo.bar.edu'); // bool