我目前正在创建一个联系表单,并且表单需要填写验证码以减少垃圾邮件,我已经遵循了有关如何在我的代码中使用验证码的教程,但每次它不起作用时,希望有人可以在这里提供帮助。任何帮助将不胜感激。
.HTML
<body>
<hgroup>
<h1>Contact Us</h1>
<?php if(isset($_GET['CaptchaPass'])){ ?>
<h3>Your message was sent, you should recieve an email back within 24
hours.</h3>
<?php } ?>
<?php if(isset($_GET['CaptchaFail'])){ ?>
<h3>Captcha Failed. Please try again!</h3>
<?php } ?>
</hgroup>
<form method='post' action='contactver.php'>
<div class="group">
<input type="text" name="name"><span class="highlight"></span><span
class="bar"></span>
<label>Name</label>
</div>
<div class="group">
<input type="email" name="email"><span class="highlight"></span><span
class="bar"></span>
<label>Email</label>
</div>
<div class="group">
<input type="phone" name="phone"><span class="highlight"></span><span
class="bar"></span>
<label>Phone No.</label>
</div>
<div class="group">
<input type="message" name="message"><span class="highlight"></span><span
class="bar"></span>
<label>Message</label>
</div>
<div class="g-recaptcha" data-
sitekey="My Key, want to keep private :)"></div>
<button type="submit" name="login" class="button buttonBlue">Submit Message
<div class="ripples buttonRipples"><span class="ripplesCircle"></span></div>
</button>
</form>
.PHP
$firstname = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
if(isset($_POST['login'])) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "Want to keep this private :)";
$response = file_get_contents($url."?
secret".$privatekey."&response=".$_POST['g-recaptcha-
response']."&remoteip".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
echo("Pass");
}else {
header('Location: contact.php?CaptchaFail=true');
echo("Fail");
}
}
您还可以在表单提交之前使用 JavaScript 进行谷歌验证码验证。
var v = grecaptcha.getResponse();
if(v.length == 0){
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
error = false;
}else{
document.getElementById('captcha').innerHTML="";
}
if(error !== false){
$('#yourformid').submit();
}
return false;
我相信这一行有问题:
if(isset($data->success) AND $data->success==true)
它应该是:
if(isset($data->success) AND $data->success===true)
除此之外,我建议使用Google Composer库(https://github.com/google/recaptcha(来验证recaptcha。它将解决您的代码行和头痛问题,因为它们会使其保持最新状态。