【问题标题】:Email address not valid when posting with php contact form使用 php 联系表发帖时电子邮件地址无效
【发布时间】:2014-10-24 22:12:50
【问题描述】:

我的脚本有问题没有发送电子邮件,返回错误消息是:电子邮件地址无效!当我在文本字段中输入我的电子邮件地址时,就会发生这种情况。我有一种感觉是(preg_match)方法造成了这个问题,但是在网上看了之后我并没有真正理解该方法的内容。希望大家帮忙,谢谢。

源代码:

  <?php
  /*Select email recipient*/
  $myemail = "info@shadowempires.url.ph";

  /*Check all form inputs using check input function*/
  $name = check_input($_POST['name'], "Please enter your name");
  $email = check_input($_POST['email'], "Please enter your email address.");
  $comment = check_input($_POST['comment'], "Please write a message.");

  /*If email is not valid show error message*/
  if (!preg_match("/(\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)){
      show_error("Email address not valid!");
  }

  /*Lets prepare the message for the email*/
  $message = "Customer Question!

  Contact form has been submitted by:

  Name: $name
  Email: $email
  Comments: $comment

  End of message";

  /*Send the message using mail() function*/
  mail($myemail, $message);

  /*Redirect visitor to the thank you page*/
  header('Location: thankyou.htm');
  exit();

  /*Functions we used*/
  function check_input($data, $problem=''){
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      if ($problem && strlen($data) == 0){
          show_error($problem);
      }
      return $data;
  }
  function show_error($myError){
  ?>
      <html>
      <body>
      <b>Please correct the following error:</b><br />
      <?php echo $myError; ?>
      </body>
      </html>
  <?php exit();
  }
  ?>

【问题讨论】:

    标签: php forms validation email


    【解决方案1】:

    filter_var呢:

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // valid email address
    }
    

    这是一种验证电子邮件地址的简单方法。

    更新 1

    看看这个答案。这里有更多关于使用正则表达式验证电子邮件地址的信息:How to validate an email address in PHP

    更新 2

    有一个测试正则表达式电子邮件模式的工具,看here

    【讨论】:

      【解决方案2】:

      你需要修复你的正则表达式,这里是一个工作的例子:

      /((\w|\-))+\@((\w|\-))+\.((\w|\-))+/
      

      【讨论】:

      • 谢谢,这让我更进一步了,我现在转到thankyou.htm,但没有发送电子邮件?电子邮件帐户存在并且正在工作!
      • @user4163554 请参阅this question/answer 进行故障排除。
      • 非常好的链接,感谢您提供正则表达式,现在一切正常。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      相关资源
      最近更新 更多