PHP ReCaptcha if else

时间:2014-01-03 17:40:20

标签: php forms validation

好的我正在尝试在发布到数据库的简单表单上实现ReCaptcha。此表单有一些不同的验证,用于验证地址对LiveAddress API和重复数据删除等是否有效

所以我试图在下面的elseif中添加ReCaptcha,这两个我的其他验证工作但是一旦它到达ReCaptcha我是否输入验证码正确或不正确当我点击提交它只是去一个空白页面。没有错误。

我的表单上有正确的公钥和私钥,以及recaptchalib.php的包含。如果您认为有用,我可以发布该代码。

我假设我需要这个在if else elseif下面因为如果我只是在表单上有所有的验证码代码,就像你下载它的例子一样忽略了验证码,它只是成功发布到DB即使你没有在验证码输入中放任何东西。

if(empty($errorMessage))
{
    // Dedupe the entry into the form
    $dupesql = "SELECT * FROM fromData WHERE (address = '$primary_number' AND city = '$city_name' AND state = '$state_abbreviation' AND zip = '$zipcode_full')";
    $duperaw = $mysqli->query($dupesql);

    // Check to make sure that they entered a valid address according to Liveaddress API
    if(empty($primary_number)){
        $bad_address .= "$bad_add in $bad_city, $bad_state is not a valid address please try again\n";
    }
    // Check to make sure that they have not already registered deduping on address, city, state, zip
    elseif($duperaw->num_rows > 0) {
        $dupe .= "$full_name already exists on $bad_add in $bad_city, $bad_state \n";
    }

    elseif( isset( $_POST["recaptcha_response_field"] ) )
    {
        $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);

        if(!$resp->is_valid) {
            echo "reCaptcha incorrect";
        } else {
            echo "reCaptcha OK";
        }
    }

    // If all "elseif" fail then we insert them into our database
    else {
        $sql = "INSERT INTO fromData (name, email, address, city, state, zip, date, optin, proccessed) VALUES ('$full_name', '$email', '$primary_number', '$city_name', '$state_abbreviation', '$zipcode_full', '$date', '$optin', 'No')";
        $mysqli->query($sql);
        echo $mysqli->error;

        header("location: index.php?success=1");
        exit();
    }
}

任何人都可以看到上面的代码明显错误吗?我一直在移动capcha代码,它仍然无法正常工作。我假设这是壁橱我必须按照我需要的方式工作。

1 个答案:

答案 0 :(得分:1)

现在的方式,最后一段代码else { ... }只有在没有先前错误(这是好的)并且用户没有为captha输入任何内容(这是坏的)时才会被执行。

这是因为如果用户为验证码输入anythnig,elseif( isset( $_POST["recaptcha_response_field"] ) )将会发生,并且最后else { ... }将不会被执行。

如果验证码正确,您要执行的代码应该在

else {
  echo "reCaptcha OK";        
} 

分支,而不是在最后else中,只有当用户保持用户对验证码的响应(我假设你保留在$_POST["recaptcha_response_field"]中)的变量为空时才执行。所以:

elseif( isset( $_POST["recaptcha_response_field"] ) ) { 
  $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"],     $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); 
  if(!$resp->is_valid) { 
    echo "reCaptcha incorrect"; 
  }
  else {
    $sql = "INSERT INTO fromData (name, email, address, city, state, zip, date, optin, proccessed) VALUES ('$full_name', '$email', '$primary_number', '$city_name', '$state_abbreviation', '$zipcode_full', '$date', '$optin', 'No')";
    $mysqli->query($sql);
    echo $mysqli->error;
    header("location: index.php?success=1");
    exit();
  } 
}