使用PHP正确验证电子邮件地址

时间:2013-01-26 17:24:28

标签: php validation email

我正在尝试编写执行以下操作的脚本: 将用户消息打印到屏幕并将其通过电子邮件发送给他们。

这是我的代码由于某种原因它告诉我,如果它是有效的电子邮件地址,我的电子邮件地址是无效的,有什么建议吗?我错过了什么? : - \

<?php
  if(strtolower($_SERVER['REQUEST_METHOD']) == 'post');

  $errors = null;
  $success = true;

  function checkEmail($email){
      return filter_var($email, FILTER_VALIDATE_EMAIL);
}

 if($_POST){
$errors = array();
$to = $_POST['email'];
$subject = 'Your Comment';
$message = $_POST['message'];
$headers = 'From: blahblah69@gmail.com' . "\r\n" . 'Reply-To:
     mitides.constantin@gmail.com' . "\r\n" .
            'X-Mailer: PHP/' .phpversion();



if(!$to || !$message){
    $errors[] ="Please fill in both a email and a message.";
} else if(!checkEmail($to) && $_POST['message'] = filter_var($_POST['message'],
   FILTER_SANITIZE_STRING));{
    $errors[]= print ('You did not enter a valid email, please try again.');
 }
 if($errors || !$_POST){

    if($errors){
        foreach($errors as $error){
            echo $error. "<br />";
        }
    }
}
if(!$errors && $success){
    mail($to, $subject, $message, $headers) && print($_POST['message']);

  } ?>

1 个答案:

答案 0 :(得分:0)

首先把else放在一个像这样的括号中 ($ _POST ['message'] = filter_var($ _ POST ['message'],FILTER_SANITIZE_STRING))