什么是验证码?
如今,当您使用表格时,您需要某种形式的保护,使其免受僵尸程序和垃圾邮件发送者的攻击。 减少垃圾邮件的一种方法是使用一种称为Captcha(验证码)的东西-它简单地将人类可读的单词放入其中,使用时必须在框中输入以证明它们是人类。 有很多免费的,我用了几个,发现Google reCaptcha非常容易安装和使用。
- jquery4ucaptcha.zip
- showform.php
- jquerycaptcha.js
- validateform.php
- recaptchalib.php
怎么运行的
解决了一个常见问题
用户输入了验证码并输入了错误的密码。 现在,当他们单击返回时,他们将丢失刚刚填写的字段中的所有表单数据! 灾害! 幸运的是,我想出了一种发送AJAX请求的方法,这样,如果验证码错误,就不会丢失任何表单输入数据。 如果验证码正确,则仅提示用户提交。
如何设置表格验证码
步骤1.您需要从Google reCaptcha网站获取自己的设置密钥。 您将同时需要两个私钥和一个公钥才能使它同时起作用。
步骤2.下载并保存recaptchalib.php 。
步骤3. jQuery代码– jquerycaptcha.js
//Validate the Recaptcha' Before continuing with POST ACTION function validateCaptcha() { challengeField = $("input#recaptcha_challenge_field").val(); responseField = $("input#recaptcha_response_field").val(); var html = $.ajax({ type: "POST", url: "../php/validateform.php", data: "form=signup&recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField, async: false }).responseText; //console.log( html ); if(html == "success") { //Add the Action to the Form $("form").attr("action", "../php/db-process-form.php"); $("#submit").attr("value", "Submit"); //Indicate a Successful Captcha $("#captcha-status").html("
Success! Thanks you may now proceed.
"); } else { $("#captcha-status").html("The security code you entered did not match. Please try again.
"); Recaptcha.reload(); } }
步骤4. PHP Code1 – validateform.php
require_once("recaptchalib.php");
$privatekey = "[yourprivatekeyhere]";
$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
echo "fail";
} else {
echo "success";
}
步骤5. PHP Code2 – showcaptcha.php
require_once("recaptchalib.php");
$publickey = "[yourpublickeyhere]";
// show the captcha
echo recaptcha_get_html($publickey);
步骤6. HTML代码
I agree to the terms-and-conditions Terms and Conditions
Type in the words below (separated by a space):
< ?php require_once("phpfunc-showcaptcha.php"); ?>
第7步。
最好的办法是隐藏验证码,直到用户填写表格或在“同意条款和条件”按钮上打勾。 这是您的操作方式。
$(document).ready(function() {
if ($('input[name=termsckb]').attr('checked') != true) {
$('#captcha-wrap').hide();
}
$('#termsckb').change(function() {
if ($('input[name=termsckb]').attr('checked') == true) {
$('#captcha-wrap').show();
$("#signupbutton").attr("value", "I am human!");
}
else {
$('#captcha-wrap').hide();
$("#signupbutton").attr("value", "Submit");
}
});
});
步骤8.自定义验证码样式
您可以更改验证码的样式和颜色以适合您的网站。 官方网站上有4种不同的选择:红色,白色,黑色和透明。
有关更多信息,请参见自定义reCAPTCHA的外观 。 我个人更喜欢clear(透明)选项。
From: https://www.sitepoint.com/setup-user-friendly-captcha-jqueryphp/