从表单提交中排除特定的电子邮件地址


Exclude a specific email address from form submission

我在其他地方看到过这个问题,但不确定如何在我的特定表单中进行一些验证,这将排除特定的电子邮件地址。如果输入了电子邮件地址,比如说,我希望表格被拒绝anything@anything.com.请参阅下面的代码。还有更多,但我相信这是相关的部分。。。

$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){
   foreach(array_keys($_COOKIE) as $value){
       unset($_REQUEST[$value]);
   }
}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
    $_REQUEST['email'] = trim($_REQUEST['email']);
    if(substr_count($_REQUEST['email'],"@") != 1 ||
       stristr($_REQUEST['email']," ") || 
       stristr($_REQUEST['email'],"''") || 
       stristr($_REQUEST['email'],":") ){
           $errors[] = "Email address is invalid";
    }
    else{
        $exploded_email = explode("@",$_REQUEST['email']);
        if (empty($exploded_email[0]) || 
            strlen($exploded_email[0]) > 64 || 
            empty($exploded_email[1])){
               $errors[] = "Email address is invalid";
        }
        else{
           if(substr_count($exploded_email[1],".") == 0){
               $errors[] = "Email address is invalid";
           }
           else{
               $exploded_domain = explode(".",$exploded_email[1]);
               if(in_array("",$exploded_domain)){
                   $errors[] = "Email address is invalid";
               }
               else{
                   foreach($exploded_domain as $value){
                       if(strlen($value) > 63 || 
                          !preg_match('/^[a-z0-9-]+$/i',$value)){
                              $errors[] = "Email address is invalid"; 
                              break;
                        }
                   }
               }
            }
          }
       }
}

如果我理解您的代码,主要部分的目标是验证用户提供的电子邮件的格式。

首先,有一个内置的php函数(php>=5.2):filter_var()。您可以将所有这些代码块替换为:

$email = trim($_REQUEST['email']);
if (!filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Email address is invalid";
}

然后,如果你想检查电子邮件是否在黑名单中,只需做这样的事情:

// Fill this array the way you want : hard-write it, fetch from database... 
$blacklist = array("email1@gmail.com", "email2@gmail.com"); 
// Put in lower case for easiest comparison
$email = strtolower($email);
if (in_array($email, $blacklist)) {
    $errors[] = "Email address is blacklisted";
}
相关文章: