没有与WordPress的CAPTCHA reCAPTCHA集成

A few weeks ago, the Google security team announced a new version of the popular reCAPTCHA system used by millions of websites in combating spam.

几周前, Google安全团队宣布了一种流行的reCAPTCHA系统的新版本,该系统已被数百万个网站用于反垃圾邮件。

For years, reCAPTCHA has prompted users to confirm they aren’t robots by asking them to read distorted text to be entered into a box, like this:

多年以来,reCAPTCHA一直要求用户阅读要输入到框中的变形文本,从而提示用户确认自己不是机器人,例如:

The Old reCAPTCHA

A lot of people griped and faulted the old reCAPTCHA system for many reasons. The distorted text it produces is difficult to recognize and bots get past the test better than humans do.

许多人出于各种原因而抓紧旧式reCAPTCHA系统并对其进行了故障。 它产生的扭曲文本很难识别,并且机器人比人类更能通过测试。

The new CAPTCHA is easy and convenient. All you need to do is click on a checkbox and you’re done. It’s also pretty effective in combating spam.

新的CAPTCHA既简单又方便。 您所需要做的就是单击一个复选框,然后完成。 在打击垃圾邮件方面也非常有效。

The New "No CAPTCHA"

Previously on SitePoint, we wrote a series on integrating the old reCAPTCHA to the following WordPress forms:

以前在SitePoint上,我们编写了一系列有关将旧的reCAPTCHA集成到以下WordPress表单的系列:

In this article, we will learn how to integrate the new No CAPTCHA reCAPTCHA with a custom form and WordPress.

在本文中,我们将学习如何将新的No CAPTCHA reCAPTCHA与自定义表单和WordPress集成在一起。

reCAPTCHA表单集成 (reCAPTCHA Form Integration)

Let’s go over the process on how to integrate reCAPTCHA with a web form.

让我们研究一下如何将reCAPTCHA与Web表单集成。

First off, head over to reCAPTCHA to grab your site and secret key.

首先,前往reCAPTCHA获取您的网站和密钥。

显示验证码 (Displaying the CAPTCHA)

Include the following to the header section of the web page: <script src="https://www.google.com/recaptcha/api.js" async defer></script>.

在网页的标题部分添加以下内容: <script src="https://www.google.com/recaptcha/api.js" async defer></script>

Add <div class="g-recaptcha" data-sitekey="your_site_key"></div> to wherever you want to output the CAPTCHA where your_site_key is your domain site/public key.

<div class="g-recaptcha" data-sitekey="your_site_key"></div>到要输出CAPTCHA的任何位置,其中your_site_key是您的域站点/公共密钥。

More information on configuring the display of the CAPTCHA widget can be found here.

此处可以找到有关配置CAPTCHA小部件的显示的更多信息。

验证用户的响应 (Verifying the User’s Response)

To verify the user response (check if the user passed or failed the CAPTCHA test), send a GET request to the URL below using either cURL, Guzzle, WordPress HTTP API or any HTTP client.

要验证用户响应(检查用户是否通过了验证码测试),请使用cURLGuzzleWordPress HTTP API或任何HTTP客户端将GET请求发送到下面的URL。

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

Where:

哪里:

your_secret: Secret (private) key. – response_string: The user response token (retrieved via PHP by $_POST['g-recaptcha-response']) ). – user_ip_address: The user IP address albeit optional. ($_SERVER["REMOTE_ADDR"]).

your_secret :秘密(专用)密钥。 – response_string :用户响应令牌(通过PHP通过$_POST['g-recaptcha-response'])检索)。 – user_ip_address :用户IP地址,尽管是可选的。 ( $_SERVER["REMOTE_ADDR"] )。

If the request was successfully sent, the response will be a JSON object similar to the one below.

如果请求已成功发送,则响应将是与以下对象相似的JSON对象。

{
  "success": true|false
}

Decode the response using json_decode() and grab success property $response['success'] which returns true if the user passes the test, or false otherwise.

使用json_decode()解码响应,并获取成功属性$response['success'] ,如果用户通过测试,则返回true,否则返回false。

More information on verifying the user response can be found here.

此处可以找到有关验证用户响应的更多信息。

reCAPTCHA WordPress集成 (reCAPTCHA WordPress Integration)

Having learned how the new No CAPTCHA reCAPTCHA can be integrated with a form, let’s also see how it can be integrated with WordPress.

了解了如何将新的No CAPTCHA reCAPTCHA与表单集成后,让我们看看如何将其与WordPress集成。

The first step is to include the plugin file header:

第一步是包括插件文件头:

<?php

/*
Plugin Name: No CAPTCHA reCAPTCHA
Plugin URI: https://www.sitepoint.com
Description: Protect WordPress login, registration and comment form from spam with the new No CAPTCHA reCAPTCHA
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
License: GPL2
*/

Enqueue the reCAPTCHA script to WordPress header section.

将reCAPTCHA脚本排队到WordPress标头部分。

// add the header script to login/registration page header
add_action( 'login_enqueue_scripts', 'header_script' );

// add CAPTCHA header script to WordPress header
add_action( 'wp_head', 'header_script' );

/** reCAPTCHA header script */
function header_script() {
echo '<script src="https://www.google.com/recaptcha/api.js" async defer></script>';
}

Next we use display_captcha() and the captcha_verification() wrapper function for displaying the CAPTCHA widget and verifying the user response.

接下来,我们使用display_captcha()captcha_verification()包装函数来显示CAPTCHA小部件并验证用户响应。

Note: change *your_site_key* and *your_secret* in the code below to your site (public) key and secret (private) key respectively.

注意:将下面代码中的* your_site_key *和* your_secret *分别更改为您的站点(公共)密钥和秘密(私有)密钥。

/** Output the reCAPTCHA form field. */
function display_captcha() {
	echo '<div class="g-recaptcha" data-sitekey="your_site_key"></div>';
}
/**
 * Send a GET request to verify CAPTCHA challenge
 *
 * @return bool
 */
function captcha_verification() {

	$response = isset( $_POST['g-recaptcha-response'] ) ? esc_attr( $_POST['g-recaptcha-response'] ) : '';

	$remote_ip = $_SERVER["REMOTE_ADDR"];

	// make a GET request to the Google reCAPTCHA Server
	$request = wp_remote_get(
		'https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=' . $response . '&remoteip=' . $remote_ip
	);

	// get the request response body
	$response_body = wp_remote_retrieve_body( $request );

	$result = json_decode( $response_body, true );

	return $result['success'];
}

We’ve now defined the base functionality of the plugin, up next is integrating the CAPTCHA with login, registration and comment forms.

现在,我们已经定义了插件的基本功能,接下来是将CAPTCHA与登录,注册和评论表单集成在一起。

登录表单 (Login Form)

Include the CAPTCHA widget to the login form by hooking the function display_captcha() to the login_form Action.

通过将函数display_captcha()挂接到login_form操作,将CAPTCHA小部件包括到登录表单中。

// adds the CAPTCHA to the login form
add_action( 'login_form', array( __CLASS__, 'display_captcha' ) );

The validate_login_captcha() function will validate and ensure the CAPTCHA checkbox isn’t left unchecked and that the test is passed.

validate_login_captcha()函数将验证并确保未选中CAPTCHA复选框,并且测试已通过。

// authenticate the CAPTCHA answer
add_action( 'wp_authenticate_user', 'validate_captcha', 10, 2 );

/**
 * Verify the CAPTCHA answer
 *
 * @param $user string login username
 * @param $password string login password
 *
 * @return WP_Error|WP_user
 */
function validate_captcha( $user, $password ) {

	if ( isset( $_POST['g-recaptcha-response'] ) && !captcha_verification() ) {
		return new WP_Error( 'empty_captcha', '<strong>ERROR</strong>: Please retry CAPTCHA' );
	}

	return $user;
}

报名表格 (Registration Form)

Include the CAPTCHA widget to the registration form by hooking the function display_captcha() to the register_form Action.

通过将函数display_captcha()挂接到register_form Action,将CAPTCHA小部件包括到注册表单中。

// adds the CAPTCHA to the registration form
add_action( 'register_form', 'display_captcha' );

Validate the CAPTCHA test in the registration form with the validate_captcha_registration_field() function hooked to registration_errors.

使用挂钩到registration_errorsvalidate_captcha_registration_field()函数来validate_captcha_registration_field()注册表单中的CAPTCHA测试。

// authenticate the CAPTCHA answer
add_action( 'registration_errors', 'validate_captcha_registration_field', 10, 3 );

/**
 * Verify the captcha answer
 *
 * @param $user string login username
 * @param $password string login password
 *
 * @return WP_Error|WP_user
 */
function validate_captcha_registration_field( $errors, $sanitized_user_login, $user_email ) {
	if ( isset( $_POST['g-recaptcha-response'] ) && !captcha_verification() ) {
		$errors->add( 'failed_verification', '<strong>ERROR</strong>: Please retry CAPTCHA' );
	}

	return $errors;
}

评论表格 (Comment Form)

First, create a global variable that will hold the status of the CAPTCHA test. That is, when a user fails the challenge, it is set to ‘failed’ and empty otherwise.

首先,创建一个全局变量,该变量将保持CAPTCHA测试的状态。 也就是说,当用户未通过挑战时,它将设置为“失败”,否则设置为空。

global $captcha_error;

Include the CAPTCHA widget to the comment form by hooking the display_captcha() function to the comment_form Action.

通过将display_captcha()函数挂接到comment_form操作上,将CAPTCHA小部件包括到注释表单中。

// add the CAPTCHA to the comment form
add_action( 'comment_form', 'display_captcha' );

The filter preprocess_comment calls the validate_captcha_comment_field() function to ensure the CAPTCHA field isn’t left empty and also that the answer is correct.

过滤器preprocess_comment调用validate_captcha_comment_field()函数,以确保CAPTCHA字段不为空,并且答案正确。

// authenticate the captcha answer
add_filter( 'preprocess_comment', 'validate_captcha_comment_field');

/**
 * Verify the captcha answer
 *
 * @param $commentdata object comment object
 *
 * @return object
 */
function validate_captcha_comment_field( $commentdata ) {
	global $captcha_error;
	if ( isset( $_POST['g-recaptcha-response'] ) && ! (captcha_verification()) ) {
		$captcha_error = 'failed';
	}

	return $commentdata;
}

The filter comment_post_redirect calls redirect_fail_captcha_comment() to delete comments detected as spam and also adds some query parameters to the comment redirection URL.

过滤器comment_post_redirect调用redirect_fail_captcha_comment()删除检测为垃圾邮件的注释,并向注释重定向URL添加一些查询参数。

add_filter( 'comment_post_redirect', 'redirect_fail_captcha_comment', 10, 2 );

/**
 * Delete spam comments
 * 
 * Add query string to the comment redirect location
 *
 * @param $location string location to redirect to after comment
 * @param $comment object comment object
 *
 * @return string
 */
function redirect_fail_captcha_comment( $location, $comment ) {
	global $captcha_error;

	if ( ! empty( $captcha_error ) ) {

		// delete the failed captcha comment
		wp_delete_comment( absint( $comment->comment_ID ) );

		// add failed query string for @parent::display_captcha to display error message
		$location = add_query_arg( 'captcha', 'failed', $location );

	}

	return $location;
}

Voila! We’re done coding the plugin.

瞧! 我们已经完成了插件的编码。

摘要 (Summary)

In this article, we learned how to protect web forms against spam using the new No CAPTCHA reCAPTCHA and finally, integrated it with the WordPress login, registration and comment forms.

在本文中,我们学习了如何使用新的No CAPTCHA reCAPTCHA保护Web表单免受垃圾邮件的侵扰,最后将其与WordPress登录,注册和评论表单集成。

If you’d like to integrate the new reCAPTCHA widget with your WordPress powered site, the plugin is available at the WordPress plugin directory.

如果您想将新的reCAPTCHA小部件与WordPress支持的网站集成在一起,则可在WordPress插件目录中使用该插件

Until I come your way again, happy coding!

直到我再次走上前,祝您编程愉快!

翻译自: https://www.sitepoint.com/no-captcha-integration-wordpress/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
什么是reCATCHA? reCATCHA是由卡内基梅隆大学发明的利用CAPTCHAs 生成的反Spam验证码,这些验证码不是随机产生的无用字符,而是从书籍上扫描下来的不容易识别的扫描字体。 这些字符又是从哪里扫描来的呢? 这就要牵涉到数字图书了,目前的“电书库”、“电图书馆”等,其中很大一部分书籍是先使用扫描仪扫描下来,然后使用 OCR 软件进行识别的。而 OCR 的识别能力有限,需要人力来一一校对,而且还不能保证完全正确,因此这样一个工程是十分浩大的。 怎样完成这个浩大的工程呢? 让全世界使用 reCAPTCHA 输入验证码的人来完成。 实现原理:reCAPTCHA 验证码中有2个单词,一个是已经正确识别出的,而另一个是未确定需要校对的单词。如下图示: 当用户输入验证码时,已经识别那个单词需要输入正确才能通过验证,而另一个不确定的单词,用户输入会反馈到 recaptcha.net,当返回一定数量的用户中绝大部分输入一致时,就确认了此单词的正确写法。 因此用户在输入验证码时,不但可以起到防SPAM的作用,还为reCAPTCHA项目校对工作作出了贡献,真是天才的创意呀! 如何在 WordPress 博客上使用reCAPTCHA呢? 对于 WordPress 博客而言,就像标题所写的那样,已经有人编写了相关的插件——WP-reCAPTCHA 该插件拥有不同的主题供选择,分别是红色、白色、黑玻璃及简洁型。 点击这里下载插件,安装方法我就不说了,要说的是使用 reCAPTCHA 必须要注册并获取API Key。下面是获取方法: 1、注册用户 点这里注册一个用户名。 2、使用域名获取 API Key 注册用户成功后,点击 Add a New Site,输入 domain(输入网站域名,二级域名、目录都可以)获取 Public Key 和 Private Key。 如何在其它类型的博客中使用reCAPTCHA呢? reCAPTCHA 可以用于各种主流编程语言,如PHP、ASP.Net、Perl以及常见程序,如WordpressphpBB、Joomla、MediaWiki。你只需点击相应的链接就可以获取到想要的 reCAPTCHA 了。 点击这里了解更多有关 reCAPTCHA 的信息。 总结:就像标题所描述的那样,这是一个创意绝佳的 WordPress 插件,其扫描字体反Spam效果肯定是不错的,现在很多网站都在用,要不你也试一试?!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值