我已经成功地在我的电子邮件表单中使用了ReCaptcha,但是我的评论部分不断收到垃圾邮件,所以我想在那里使用它。
然而,我不确定如何实现验证码验证码。
我的电子邮件表单使用第二个页面来发布数据,所以它工作得很好,但是我的评论表单有所有的php代码在同一个页面上发布表单。
当我尝试像以前那样输入验证码时,但是在同一页面上发布代码,这会导致整个页面在加载时变为空白。
错误报告:
注意:未定义索引:在/_assets/commentBox/podcastHeader.php第36行
注意:未定义索引:在/_assets/commentBox/podcastHeader.php第37行
验证码输入不正确。回去再试一次。(验证码显示:incorrect-captcha-sol)
所以我猜它试图立即找到reCaptcha表单,但失败了,因为还没有填写任何内容。
这是我使用的相关代码:
<?php
require_once('../../_assets/recaptchalib.php');
$privatekey = "xxxxxx ";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
if (isset($_POST['submit'])) {
$required_fields = array("author", "body");
validate_presences($required_fields);
if (empty($errors)) {
$author = mysql_prep($_POST['author']);
$body = mysql_prep($_POST['body']);
$page_name = ($_POST['page_name']);
$current_time = date("Y-m-d H-i-s");
$query = "INSERT INTO comments (";
$query .= " author, body, page_name, created";
$query .= ") VALUES (";
$query .= " '{$author}', '{$body}', '{$page_name}', '{$current_time}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
redirect_to("{$url}{$anchor}");
} else {
// Failure
$_SESSION["message"] = "There was an error that prevented the comment from being saved.";
}
}
} else {
$author = "";
$body = "";
}
}
$display_comments = find_comments();
?>
这是注释表单:
<div id="newComment">
<h3 id="leaveComment">Leave a Comment!</h3>
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<form action="<?php echo $url; ?>#comments" method="post">
<input type="hidden" name="page_name" value="<?=$_SERVER['REQUEST_URI']?>" />
<input type="text" name="author" placeholder="Nickname" value="<?php echo $author; ?>" /><br>
<textarea name="body" style="margin-top:5px" cols="40" rows="8" placeholder="What's on your mind?"><?php echo $body; ?></textarea><br>
<div style="margin-top: 6px">
<?php
require_once('../../_assets/recaptchalib.php');
$publickey = "xxxxxx";
echo recaptcha_get_html($publickey);
?>
</span>
<input type="submit" style="margin-top:10px" name="submit" value="Submit" />
<span style="margin-left: 8px">
<a href="#title">Return to top</a>
</div>
</form>
</div>
$resp = recaptcha_check_answer ($privatekey,$ _SERVER("REMOTE_ADDR"),$ _POST["recaptcha_challenge_field"),$ _POST [" recaptcha_response_field "]);
这一行立即检查结果,由于之前没有对POST数据进行检查,因此页面将在执行任何操作之前死亡。
将检查符放入条件:
if (isset($_POST['submit'])) {
$resp = recaptcha_check_answer(...);
if (!$resp->is_valid) {
// Wrong captcha
}
}