防止在错误的验证码值上提交表单

时间:2012-11-06 15:51:16

标签: forms captcha form-submit

您好我使用了基本的验证码脚本,如下所示。我面临的问题是,尽管验证码价值不对,但表格仍然提交。如果Captcha的值输入错误,我需要阻止提交表单。

<?php
  if(isset($_POST['submit']))
{
  $hash = (!empty($_POST['hash'])) ? preg_replace('/[\W]/i', '', trim($_POST['hash'])) : ''; // Remove any non alphanumeric characters to prevent exploit attempts
  $captchacode = (!empty($_POST['captchacode'])) ? preg_replace('/[\W]/i', '', trim($_POST['captchacode'])) : ''; // Remove any non alphanumeric characters to prevent exploit attempts
  // function to check the submitted captcha
  function captchaChars($hash)
  {
    //  Generate a 32 character string by getting the MD5 hash of the servers name with the hash added to the end.
    //  Adding the servers name means outside sources cannot just work out the characters from the hash
    $captchastr = strtolower(md5($_SERVER['SERVER_NAME'] . $hash));
    $captchastr2 = '';
    for($i = 0; $i <= 28; $i += 7)
    {
      $captchastr2 .= $captchastr[$i];
    }
    return $captchastr2;
  }
  if(!empty($captchacode))
  {
    if(strtolower($captchacode) == captchaChars($hash))  // We convert submitted characters to lower case then compare with the expected answer
    {
      echo '<h3>The submitted characters were correct</h3>';

    }
    else
    {
      echo '<h3>The submitted characters were WRONG!</h3>';
       return true;
    }

  }

  else
  {
    echo '<h3>You forgot to fill in the code!</h3>';
    return true;
  }

}
?>  

1 个答案:

答案 0 :(得分:0)

我在我的网站上运行了Captcha并且它没有阻止垃圾邮件。它害怕被视为垃圾邮件预防机制。

除此之外,如果验证码不正确并且不提交表单,则需要返回false。