PHP表单垃圾邮件预防

时间:2014-03-15 05:19:39

标签: php html forms validation spam-prevention

请耐心等待我,因为我是一名具有一定编码知识的平面设计师,但并不像开发人员那么近。经过几个小时的修修和问Google之后,我决定直接问问所有人!

我一直致力于为我的网站建立联系表格。到目前为止一切都那么好,除了一件事。我想添加一个简单的垃圾邮件预防字段。

我已经添加了一个字段" spamcheck"问题6 + 2 =?但我不知道如何编写PHP以要求值特别是8.只要其他字段被正确填写,表单将提交,无论在此处输入的数字,尽管任何试图弄乱代码(因此为什么你会看到我的$ spamcheck变量,但当前的编码只要求它有一个像其他字段一样的值。)

我已经包含了PHP,PHP调用的验证以及表单。如果表单有一些多余的代码,请道歉;我尝试了许多不同版本的PHP表单教程无济于事。

当然,非常感谢你的帮助! :)

以下是我直接放在网页中的PHP代码:

<?php 
define("EMAIL", "email@gmail.com");

if(isset($_POST['submit'])) {

  include('validate.class.php');

  //assign post data to variables 
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $budget = trim($_POST['budget']);
    $deadline = trim($_POST['deadline']);
    $message = trim($_POST['message']);
    $spamcheck = trim($_POST['spamcheck']);

  //start validating our form
  $v = new validate();
  $v->validateStr($name, "name", 1, 50);
  $v->validateEmail($email, "email");
  $v->validateStr($budget, "budget");
  $v->validateStr($deadline, "deadline");
  $v->validateStr($message, "message", 1, 1000);
  $v->validateStr($spamcheck, "spamcheck");

  if(!$v->hasErrors()) {
       $from = "website.com"; //Site name
  // Change this to your email address you want to form sent to
  $to = "email@gmail.com"; 
  $subject = "Hello! Comment from " . $name . "";

  $message = "Message from " . $name . "
  Email: " . $email . " 
  Budget: " . $budget ."
  Deadline: " . $deadline ."
  Message: " . $message ."";
  mail($to,$subject,$message,$from);


    //grab the current url, append ?sent=yes to it and then redirect to that url
        $url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        header('Location: '.$url."?sent=yes");

    } else {
    //set the number of errors message
    $message_text = $v->errorNumMessage();       

    //store the errors list in a variable
    $errors = $v->displayErrors();

    //get the individual error messages
    $nameErr = $v->getError("name");
    $emailErr = $v->getError("email");
    $budgetErr = $v->getError("budget");
    $deadlineErr = $v->getError("deadline");
    $messageErr = $v->getError("message");
    $spamcheckErr = $v->getError("spamcheck");

  }//end error check
}// end isset
  ?>

这是它调用的validate.class.php:

<?php
class validate {

  public $errors = array();

   public function validateStr($postVal, $postName, $min = 1, $max = 1000) {
    if(strlen($postVal) < intval($min)) {
      $this->setError($postName, ucfirst($postName)." is required.");
    } else if(strlen($postVal) > intval($max)) {
      $this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
    }
  }// end validateStr

   public function validateEmail($emailVal, $emailName) {
    if(strlen($emailVal) <= 0) {
      $this->setError($emailName, "Please enter an Email Address");
    } else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
      $this->setError($emailName, "Please enter a Valid Email Address");
        }
  }// end validateEmail     

  private function setError($element, $message) {
    $this->errors[$element] = $message;
  }// end logError


  public function getError($elementName) {
    if($this->errors[$elementName]) {
      return $this->errors[$elementName];
    } else {
      return false;
    }
  }// end getError

  public function displayErrors() {
    $errorsList = "<ul class=\"errors\">\n";
    foreach($this->errors as $value) {
      $errorsList .= "<li>". $value . "</li>\n";
    }
    $errorsList .= "</ul>\n";
    return $errorsList;
  }// end displayErrors

  public function hasErrors() {
    if(count($this->errors) > 0) {
      return true;
    } else {
      return false;
    }
  }// end hasErrors

  public function errorNumMessage() {
    if(count($this->errors) > 1) {
            $message = "There was an error sending your message!\n";
        } else {
            $message = "There was an error sending your message!\n";
        }
    return $message;
  }// end hasErrors

}// end class
?>

这是表格html / php:

<span class="message"><?php echo $message_text; ?></span>
   <?php if(isset($_GET['sent'])): ?><h2>Your message has been sent</h2><?php endif; ?>
          <form role="form" method="post" action="webpage.php#contact">
            <div class="form-group">
              <input type="text" name="name" class="form-control" id="name" value="<?php echo htmlentities($name); ?>" placeholder="Full Name" required>
              <label for="exampleInputName"><i class="icon-tag"></i></label>
              <span class="errors"><?php echo $nameErr; ?></span>
              <div class="clearfix"></div>
            </div>
            <div class="form-group">
              <input type="email" name="email" class="form-control" id="email" value="<?php echo htmlentities($email); ?>" placeholder="Email" required>
              <label for="exampleInputEmail1"><i class="icon-inbox"></i></label>
              <span class="errors"><?php echo $emailErr; ?></span>
              <div class="clearfix"></div>
            </div>
            <div class="form-group">
              <input type="text" name="budget" class="form-control" id="budget" value="<?php echo htmlentities($budget); ?>" placeholder="Budget" required>
              <label for="exampleInputBudget1"><i class="icon-usd"></i></label>
              <span class="errors"><?php echo $budgetErr; ?></span>
              <div class="clearfix"></div>
            </div>
            <div class="form-group">
              <input type="text" name="deadline" class="form-control" id="deadline" value="<?php echo htmlentities($deadline); ?>" placeholder="Deadline" required>
              <label for="exampleInputDeadline"><i class="icon-calendar"></i></label>
              <span class="errors"><?php echo $deadlineErr; ?></span>
              <div class="clearfix"></div>
            </div>
            <div class="form-group textarea">
              <textarea rows="6" name="message" class="form-control" id="message" value="<?php echo htmlentities($message); ?>" placeholder="Write Message" required></textarea>
              <label for="exampleInputMessage"><i class="icon-pencil"></i></label>
              <span class="errors"><?php echo $messageErr; ?></span>
              <div class="clearfix"></div>
            </div>
            <div class="form-group">
              <input type="text" name="spamcheck" class="form-control" id="spamcheck" value="<?php echo htmlentities($spamcheck); ?>" placeholder="Spam check: 6+2=?" required>
              <label for="exampleInputSpamCheck"><i class="icon-lock"></i></label>
              <span class="errors"><?php echo $spamcheckErr; ?></span>
              <div class="clearfix"></div>
            </div>

            <button type="submit" id="submit" name="submit" value="submit" class="btn btn-large">Send Message</button>
          </form>

2 个答案:

答案 0 :(得分:3)

在生成表单的PHP脚本中,您应该在$_SESSION variable中保存问题的正确答案。

然后,在接收此表单数据的PHP脚本中,您应该验证为该问题提交的内容是否与$_SESSION变量中的正确答案匹配。

如何在PHP中使用会话有很多tutorials

基本上,它归结为:

<强> form.php的

<?php
    session_start();
    $_SESSION['captcha_right_answer'] = somehow_generate_this();
?>

<强> handler.php

<?php
    session_start();

    if ($_INPUT['captcha_answer'] != $_SESSION['captcha_right_answer']) {
        // Show "bad captcha" message, re-show form, whatever
    }
    else {
        // Captcha good - go on with life
    }
?>

答案 1 :(得分:1)

this作为验证码的替代方案。然后,您可以使用现有的类来验证该字段。假设您的隐藏字段名称为“fakeField”您可以使用validateSTR方法通过..

对其进行验证
$v->validateStr($fakeField, "fakeField",0,0);

由于您的str检查正在检查&gt;和&lt;而不是&gt; =和&lt; =当长度正好为0时,这将返回true。对于那些代码知识很少的人来说,这可能是一个更容易的解决方案。

或者,如果你坚持使用排序验证码,并且你知道你期望值是什么,你可以添加一个方法来检查你期望的值。

方法:

public function validateCaptcha( $value,$name, $expectedValue) {
if(trim($value) != $expectedValue) {
  $this->setError($name, "Captcha Incorrect");
    }
}

然后更改代码行

$v->validateStr($spamcheck, "spamcheck");

$v->validateCaptcha($spamcheck, "spamcheck", '6');

这不是最好的解决方案,因为有很多强大的验证码,但它很容易使用。