>本教程演示了构建一个WordPress插件,该插件将Google Recaptcha集成到WordPress登录系统中。 该插件使用HTTP API发送邮政请求以recaptcha,验证了用户验证验响应。
>。 这是通过将人类与机器人区分开来的,防止未经授权的访问尝试来增强网站的安全性。https://www.google.com/recaptcha/api/verify
>
是具有集成验证码的WordPress登录表格的屏幕截图:
>插件开发
在编码之前,请在Recaptcha上注册您的域,并获取您的公共和私有API键。
1。插件标题:
2。 PHP类:
<code class="language-php"><?php /* Plugin Name: WP Login Form with reCAPTCHA Plugin URI: https://www.sitepoint.com Description: Adds Google's reCAPTCHA to WordPress Login Version: 1.0 Author: Agbonghama Collins Author URI: http://w3guy.com License: GPL2 */</code>
创建一个PHP类以存储recaptcha键:
3。插件实例:<code class="language-php">class reCAPTCHA_Login_Form { private $public_key, $private_key; public function __construct() { $this->public_key = '6Le6d-USAAAAAFuYXiezgJh6rDaQFPKFEi84yfMc'; $this->private_key = '6Le6d-USAAAAAKvV-30YdZbdl4DVmg_geKyUxF6b'; add_action( 'login_form', array( $this, 'captcha_display' ) ); add_action( 'wp_authenticate_user', array( $this, 'validate_captcha_field' ), 10, 2 ); } public function captcha_display() { ?> <noscript> <iframe src="https://www.google.com/recaptcha/api/noscript?k=<?=%24this->public_key?>" height="300" width="300" frameborder="0"></iframe><br><br> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"> </noscript> <?php } public function validate_captcha_field($user, $password) { if ( ! isset( $_POST['recaptcha_response_field'] ) || empty( $_POST['recaptcha_response_field'] ) ) { return new WP_Error( 'empty_captcha', 'CAPTCHA cannot be empty' ); } if( isset( $_POST['recaptcha_response_field'] ) && $this->recaptcha_response() === 'false' ) { return new WP_Error( 'invalid_captcha', 'Incorrect CAPTCHA response' ); } return $user; } public function recaptcha_response() { $challenge = isset($_POST['recaptcha_challenge_field']) ? esc_attr($_POST['recaptcha_challenge_field']) : ''; $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 ); } public function recaptcha_post_request( $post_body ) { $args = array( 'body' => $post_body ); $request = wp_remote_post( 'https://www.google.com/recaptcha/api/verify', $args ); $response_body = wp_remote_retrieve_body( $request ); $answers = explode( "\n", $response_body ); $request_status = trim( $answers[0] ); return $request_status; } } new reCAPTCHA_Login_Form();</code>
最后,实例化类:
这完成了插件代码。 下载完整的插件以供使用或进一步研究。 这是在插件中演示WordPress HTTP API使用的系列的一部分。
<code class="language-php">new reCAPTCHA_Login_Form();</code>>(FAQS部分是为了简洁的,因为它不需要重写伪 - 原始性。内容是事实,不需要更改。
以上是将验证验与WordPress登录表单集成的详细内容。更多信息请关注PHP中文网其他相关文章!