>本教程演示了構建一個WordPress插件,該插件將Google Recaptcha集成到WordPress登錄系統中。 該插件使用HTTP API發送郵政請求以recaptcha,驗證了用戶驗證驗響應。
>。 這是通過將人類與機器人區分開來的,防止未經授權的訪問嘗試來增強網站的安全性。 https://www.google.com/recaptcha/api/verify
>
是具有集成驗證碼的WordPress登錄表格的屏幕截圖:
>插件開發
在編碼之前,請在Recaptcha上註冊您的域,並獲取您的公共和私有API鍵。
1。插件標題:
2。 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 */
創建一個PHP類以存儲recaptcha鍵:
3。插件實例: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=<?=$this->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();
最後,實例化類:
這完成了插件代碼。 下載完整的插件以供使用或進一步研究。 這是在插件中演示WordPress HTTP API使用的系列的一部分。
new reCAPTCHA_Login_Form();
以上是將驗證驗與WordPress登錄表單集成的詳細內容。更多資訊請關注PHP中文網其他相關文章!