只允许以@gmail.com结尾的邮件

  • 本文关键字:结尾 com @gmail php
  • 更新时间 :
  • 英文 :


这个Github存储库用于向Gmail地址添加点(.),从而使用从原始地址派生的随机地址在网站上多次注册。

代码工作正常,但它适用于任何域(例如@house.com)

我需要限制它只与@gmail.com工作(我在我的HTML中尝试过)<input type="email" pattern="^[a-zA-Z0-9]+@gmail.com$">

但是我更喜欢服务器端,我不知道怎么做,我是PHP的新手。

提前感谢。

PHP代码:

<?php
set_time_limit(0);
if(isset($_POST['email']))
{
$mail = explode('@', $_POST['email']);
$email = $mail[0];
$domain = '@'.$mail[1];
$email = ltrim($email);
$domain = ltrim($domain);
$email = rtrim($email);
$domain = rtrim($domain);
$email = stripslashes($email);
$domain = stripslashes($domain);
$email = htmlentities($email);
$domain = htmlentities($domain);
$res = addDOT($email);
echo '<div class="box"><div class="title">Total: '.sizeof($res).'</div><textarea type="text">';
foreach($res as $mcMails)
{
echo nl2br($mcMails.$domain).PHP_EOL;
}
echo '</textarea></div>';
}
function addDOT($str){ 
if(strlen($str) > 1)
{
$ca = preg_split("//",$str); 
array_shift($ca); 
array_pop($ca); 
$head = array_shift($ca); 
$res = addDOT(join('',$ca)); 
$result = array(); 
foreach($res as $val)
{ 
$result[] = $head . $val; 
$result[] = $head . '.' .$val; 
} 
return $result; 
} 
return array($str); 
}
?>

在PHP 8+中可以使用str_ends_with()

function isGmail($email) {
return str_ends_with($email, '@gmail.com');
}

或使用经典正则表达式

的旧PHP8+
function isGmail($email) {
return preg_match("/@gmail.com$/", $email);
}

或带负偏移量

的字符串
function isGmail($email) {
$pattern = '@gmail.com';
return (false !== strpos($email, $pattern, -strlen($pattern)));
}

更新根据你的评论,我认为你应该这样做:

$email = $_POST['email'] ?? '';
if(!isGmail($email)) {
header('Location: /');
exit();
}
<?php
set_time_limit(0);
if(isset($_POST['email']))
{
if(isGmail($_POST['email'])){
$mail = explode('@', $_POST['email']);
$email = $mail[0];
$domain = '@'.$mail[1];
$email = ltrim($email);
$domain = ltrim($domain);
$email = rtrim($email);
$domain = rtrim($domain);
$email = stripslashes($email);
$domain = stripslashes($domain);
$email = htmlentities($email);
$domain = htmlentities($domain);
$res = addDOT($email);
echo '<div class="box"><div class="title">Total:'.sizeof($res).'</div><textarea type="text">';
foreach($res as $mcMails)
{
echo nl2br($mcMails.$domain).PHP_EOL;
}
echo '</textarea></div>';
}
}
function addDOT($str){ 
if(strlen($str) > 1)
{
$ca = preg_split("//",$str); 
array_shift($ca); 
array_pop($ca); 
$head = array_shift($ca); 
$res = addDOT(join('',$ca)); 
$result = array(); 
foreach($res as $val)
{ 
$result[] = $head . $val; 
$result[] = $head . '.' .$val; 
} 
return $result; 
} 
return array($str); 
}
/**
* Check if an email is a Gmail address
* @param string $email The email address to check
* @return boolean
*/
function isGmail($email) {
$email = trim($email); // in case there's any whitespace
return mb_substr($email, -10) === '@gmail.com';
}
?>

修复。我通过添加第二个条件修改了代码的第一个if:

if(isset($_POST['email']) and (substr($_POST['email'], -10) == '@gmail.com'))

相关内容

  • 没有找到相关文章

最新更新