java captcha

tech2023-01-23  58

java captcha

Over the years, WordPress has become a target for spammers due to it increasing popularity.

多年来,由于WordPress越来越受欢迎,它已成为垃圾邮件发送者的目标。

Unfortunately, automated software exists whose purpose is to crawl the web in search of websites that are built with any popular platform, such as WordPress, and to submit hundreds, even thousands of spam comments. Spam comments are very annoying, they consume our precious time when it comes to moderating and deleting them.

不幸的是,存在自动软件,其目的是爬网以搜索使用任何流行平台(例如WordPress)构建的网站,并提交数百甚至数千条垃圾评论。 垃圾评论非常烦人,在审核和删除它们时会浪费我们宝贵的时间。

I know you hate spam comments as much as I do and would love to know how to combat them. One way of deterring bots from submitting spam comments is by integrating a CAPTCHA to the comment form.

我知道您和我一样讨厌垃圾邮件评论,并且很想知道如何与他们作斗争。 阻止漫游器提交垃圾邮件评论的一种方法是将CAPTCHA集成到评论表单中。

In previous tutorials, we learned how to integrate CAPTCHAs to the WordPress login and registration form.

在之前的教程中,我们学习了如何将CAPTCHA与WordPress 登录和注册表单集成。

In similar fashion, we’ll now run through how to integrate a CAPTCHA with the WordPress comment system.

现在,我们将以类似的方式介绍如何将CAPTCHA与WordPress注释系统集成。

There are many CAPTCHA plugins available in the WordPress plugin directory such as WP-reCAPTCHA and Securimage-WP-Fixed.

WordPress插件目录中有许多可用的CAPTCHA插件 ,例如WP-reCAPTCHA和Securimage-WP-Fixed 。

The aim of this tutorial is to not create yet another CAPTCHA plugin but to:

本教程的目的不是创建另一个验证码插件,而是:

Demonstrate how the WordPress HTTP API can be used in a plugin.

演示如何在插件中使用WordPress HTTP API 。

How to include additional form fields to the WordPress comment form.

如何在WordPress注释表单中包括其他表单字段。 How to validate and utilise the values added to custom fields.

如何验证和利用添加到自定义字段的值。

Without further ado, let’s get started with the plugin development.

事不宜迟,让我们开始进行插件开发。

插件开发 (Plugin Development)

First off, head over to reCAPTCHA, register your domain name and grab your public and private API keys.

首先,前往reCAPTCHA ,注册您的域名并获取您的公共和私有API密钥。

Include the plugin header.

包括插件头。

<?php /* Plugin Name: Add reCAPTCHA to comment form Plugin URI: https://www.sitepoint.com Description: Add Google's reCAPTCHA to WordPress comment form Version: 1.0 Author: Agbonghama Collins Author URI: http://w3guy.com License: GPL2 */

Create a class with three properties that will store the reCAPTCHA’s private & public key as well as the CAPTCHA error message (errors are generated when the CAPTCHA form is left empty and a user fails the challenge).

创建一个具有三个属性的类,这些属性将存储reCAPTCHA的私钥和公钥以及CAPTCHA错误消息(当CAPTCHA表单保留为空并且用户未通过质询时会生成错误)。

class Captcha_Comment_Form { /** @type string private key|public key */ private $public_key, $private_key; /** @type string captcha errors */ private static $captcha_error;

The class magic constructor method will contain two pairs of action and filter hooks.

类Magic构造函数方法将包含两对action和filter钩子。

/** class constructor */ public function __construct() { $this->public_key = '6Le6d-USAAAAAFuYXiezgJh6rDaQFPKFEi84yfMc'; $this->private_key = '6Le6d-USAAAAAKvV-30YdZbdl4DVmg_geKyUxF6b'; // adds the captcha to the WordPress form add_action( 'comment_form', array( $this, 'captcha_display' ) ); // delete comment that fail the captcha challenge add_action( 'wp_head', array( $this, 'delete_failed_captcha_comment' ) ); // authenticate the captcha answer add_filter( 'preprocess_comment', array( $this, 'validate_captcha_field' ) ); // redirect location for comment add_filter( 'comment_post_redirect', array( $this, 'redirect_fail_captcha_comment' ), 10, 2 ); }

Code explanation: First, my reCAPTCHA public and private keys are saved to their class properties.

代码说明:首先,将我的reCAPTCHA公钥和私钥保存到其类属性中。

The captcha_display() method that will output the reCAPTCHA challenge is added to the comment form by the comment_form Action.

comment_form操作会将将输出reCAPTCHA质询的captcha_display()方法添加到注释表单中。

The wp_head Action includes the callback function delete_failed_captcha_comment() that will delete any comment submitted that fail the CAPTCHA challenge.

wp_head操作包含回调函数delete_failed_captcha_comment() ,该函数将删除提交的所有未通过验证码的注释。

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

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

The filter comment_post_redirect call redirect_fail_captcha_comment() to add some query parameters to the comment redirection URL.

过滤器comment_post_redirect调用redirect_fail_captcha_comment()将一些查询参数添加到注释重定向URL。

Here is the code for captcha_display() that will output the CAPTCHA challenge.

这是captcha_display()的代码,将输出验证码挑战。

Additionally, it check if there is a query string attached to the current page URL and display the appropriate error message depending on the value of $_GET['captcha'] set by redirect_fail_captcha_comment()

此外,它还会检查当前页面URL是否附加了查询字符串,并根据redirect_fail_captcha_comment()设置的$_GET['captcha']的值显示相应的错误消息。

/** Output the reCAPTCHA form field. */ public function captcha_display() { if ( isset( $_GET['captcha'] ) && $_GET['captcha'] == 'empty' ) { echo '<strong>ERROR</strong>: CAPTCHA should not be empty'; } elseif ( isset( $_GET['captcha'] ) && $_GET['captcha'] == 'failed' ) { echo '<strong>ERROR</strong>: CAPTCHA response was incorrect'; } echo <<<CAPTCHA_FORM <style type='text/css'>#submit { display: none; }</style> <script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=<?= $this->public_key; ?>"> </script> <noscript> <iframe src="http://www.google.com/recaptcha/api/noscript?k=<?= $this->public_key; ?>" height="300" width="300" frameborder="0"></iframe> <br> <textarea name="recaptcha_challenge_field" rows="3" cols="40"> </textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"> </noscript> <input name="submit" type="submit" id="submit-alt" tabindex="6" value="Post Comment"/> CAPTCHA_FORM; } /** * 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 ) { if ( ! empty( self::$captcha_error ) ) { $args = array( 'comment-id' => $comment->comment_ID ); if ( self::$captcha_error == 'captcha_empty' ) { $args['captcha'] = 'empty'; } elseif ( self::$captcha_error == 'challenge_failed' ) { $args['captcha'] = 'failed'; } $location = add_query_arg( $args, $location ); } return $location; }

The method validate_captcha_field() as its name implies to validate the CAPTCHA answer by making sure the CAPTCHA field isn’t left empty and the supplied answer is correct.

方法validate_captcha_field()的名称暗示要通过确保验证码字段不为空并且提供的答案正确来验证验证码答案。

/** * Verify the captcha answer * * @param $commentdata object comment object * * @return object */ public function validate_captcha_field( $commentdata ) { // if captcha is left empty, set the self::$captcha_error property to indicate so. if ( empty( $_POST['recaptcha_response_field'] ) ) { self::$captcha_error = 'captcha_empty'; } // if captcha verification fail, set self::$captcha_error to indicate so elseif ( $this->recaptcha_response() == 'false' ) { self::$captcha_error = 'challenge_failed'; } return $commentdata; }

Let’s take a closer look at validate_captcha_field(), specifically the elseif conditional statement, a call is made to recaptcha_response() to check if the CAPTCHA answer is correct.

让我们仔细看一下validate_captcha_field() ,特别是elseif条件语句,调用recaptcha_response()来检查CAPTCHA答案是否正确。

Below is the code for the recaptcha_response().

以下是recaptcha_response()的代码。

/** * Get the reCAPTCHA API response. * * @return string */ public function recaptcha_response() { // reCAPTCHA challenge post data $challenge = isset( $_POST['recaptcha_challenge_field'] ) ? esc_attr( $_POST['recaptcha_challenge_field'] ) : ''; // reCAPTCHA response post data $response = isset( $_POST['recaptcha_response_field'] ) ? esc_attr( $_POST['recaptcha_response_field'] ) : ''; $remote_ip = $_SERVER["REMOTE_ADDR"]; $post_body = array( 'privatekey' => $this->private_key, 'remoteip' => $remote_ip, 'challenge' => $challenge, 'response' => $response ); return $this->recaptcha_post_request( $post_body ); }

Allow me to explain how the recaptcha_response() works.

请允许我解释一下recaptcha_response()工作方式。

A POST request is sent to the endpoint http://www.google.com/recaptcha/api/verify with the following parameters.

使用以下参数将POST请求发送到端点http://www.google.com/recaptcha/api/verify 。

privatekey: Your private key

privatekey :您的私钥

remoteip The IP address of the user who solved the CAPTCHA.

remoteip解决了验证码的用户的IP地址。

challenge The value of recaptcha_challenge_field sent via the form.

challenge通过表单发送的recaptcha_challenge_field的值。

response The value of recaptcha_response_field sent via the form.

response通过表单发送的recaptcha_response_field的值。

The challenge and response POST data sent by the form is captured and saved to $challenge and $response respectively.$_SERVER["REMOTE_ADDR"] capture the user’s IP address and it to $remote_ip.

捕获由表单发送的质询和响应POST数据,并将其分别保存到$challenge和$response 。 $_SERVER["REMOTE_ADDR"]捕获用户的IP地址并将其保存到$remote_ip 。

WordPress HTTP API the POST parameter to be in array form hence the code below.

WordPress HTTP API的POST参数为数组形式,因此代码如下。

$post_body = array( 'privatekey' => $this->private_key, 'remoteip' => $remote_ip, 'challenge' => $challenge, 'response' => $response ); return $this->recaptcha_post_request( $post_body );

The recaptcha_post_request() is a wrapper function for the HTTP API which will accept the POST parameter/body, make a request to the reCAPTCHA API and return true if the CAPTCHA test was passed and false otherwise.

recaptcha_post_request()是HTTP API的包装函数,它将接受POST参数/正文,向reCAPTCHA API发出请求,如果通过了验证码,则返回true否则返回false 。

/** * Send HTTP POST request and return the response. * * @param $post_body array HTTP POST body * * @return bool */ public function recaptcha_post_request( $post_body ) { $args = array( 'body' => $post_body ); // make a POST request to the Google reCaptcha Server $request = wp_remote_post( 'https://www.google.com/recaptcha/api/verify', $args ); // get the request response body $response_body = wp_remote_retrieve_body( $request ); /** * explode the response body and use the request_status * @see https://developers.google.com/recaptcha/docs/verify */ $answers = explode( "\n", $response_body ); $request_status = trim( $answers[0] ); return $request_status; }

Any comment made by a user who failed the captcha challenge or left the field empty get deleted by delete_failed_captcha_comment()

验证码挑战失败或将该字段留空的用户发表的任何评论都可以通过delete_failed_captcha_comment()删除

/** Delete comment that fail the captcha test. */ function delete_failed_captcha_comment() { if ( isset( $_GET['comment-id'] ) && ! empty( $_GET['comment-id'] ) ) { wp_delete_comment( absint( $_GET['comment-id'] ) ); } }

Finally, we close the plugin class.

最后,我们关闭插件类。

} // Captcha_Comment_Form

We are done coding the plugin class. To put the class to work, we need to instantiate it like so:

我们已经完成了插件类的编码。 为了使该类正常工作,我们需要像这样实例化它:

new Captcha_Comment_Form();

On activation of the plugin, a CAPTCHA will be added to the WordPress comment form as show below.

激活插件后,CAPTCHA将添加到WordPress注释表单中,如下所示。

结语 (Wrap Up)

At the end of this tutorial, you should be able to add extra form fields to the comment form and implement just about any feature you wish to have in the comment system thanks to the filters and actions mentioned.

在本教程的最后,由于提到的过滤器和操作 ,您应该能够在注释表单中添加额外的表单字段,并实现您希望在注释系统中拥有的几乎所有功能。

If you wish to use the plugin on your WordPress site or to study the code in-depth, download the plugin from GitHub.

如果您希望在WordPress网站上使用该插件或深入研究代码,请从GitHub 下载该插件 。

Until I come your way again, happy coding!

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

翻译自: https://www.sitepoint.com/integrating-a-captcha-with-the-wordpress-comment-form/

java captcha

最新回复(0)