Fight Registration Spam with Google's ReCaptcha (ok)
https://code.tutsplus.com/tutorials/build-a-custom-wordpress-user-flow-part-2-new-user-registration--cms-23810
"Test V2"
Site Key: 6LfjxU0gAAAAAEsTA9MARMZidFTRd7Ixh4Kzqywe Secret Key: 6LfjxU0gAAAAAIp_A7aGb3NWPTg_lNRKTQnh0SLN 'Test Local' has been registered. Site Key: 6LcKr00gAAAAAKIP9h4lxBLFIDuOAEJDv3Vzm-Ky
Secret Key: 6LcKr00gAAAAAGBDO-4GktKgGsg4xphIx_qHIFKi
Sử dụng "Test V2"
C:\xampp\htdocs\reset3\wp-content\plugins\personalize-login\personalize-login.php
<?php
/**
* Plugin Name: Personalize Login
* Description: A plugin that replaces the WordPress login flow with a custom page.
* Version: 1.0.0
* Author: Jarkko Laine
* License: GPL-2.0+
* Text Domain: personalize-login
*/
class Personalize_Login_Plugin {
/**
* Initializes the plugin.
*
* To keep the initialization fast, only add filter and action
* hooks in the constructor.
*/
public function __construct() {
add_shortcode( 'custom-register-form', array( $this, 'render_register_form' ) );
add_action( 'login_form_register', array( $this, 'redirect_to_custom_register' ) );
add_action( 'login_form_register', array( $this, 'do_register_user' ) );
// Capchar
add_filter( 'admin_init' , array( $this, 'register_settings_fields' ) );
add_action( 'wp_print_footer_scripts', array( $this, 'add_captcha_js_to_footer' ) );
}
/**
* Plugin activation hook.
*
* Creates all WordPress pages needed by the plugin.
*/
public static function plugin_activated() {
$page_definitions = array(
'member-login' => array(
'title' => __( 'Sign In', 'personalize-login' ),
'content' => '[custom-login-form]'
),
'member-account' => array(
'title' => __( 'Your Account', 'personalize-login' ),
'content' => '[account-info]'
),
'member-register' => array(
'title' => __( 'Register', 'personalize-login' ),
'content' => '[custom-register-form]'
));
foreach ($page_definitions as $slug => $page) {
$query = new WP_Query('pagename=' . $slug);
if (!$query->have_posts()) {
wp_insert_post(
array(
'post_content' => $page['content'],
'post_name' => $slug,
'post_title' => $page['title'],
'post_status' => 'publish',
'post_type' => 'page',
'ping_status' => 'closed',
'comment_status' => 'closed',
)
);
}
}
}
/**
* Renders the contents of the given template to a string and returns it.
*
* @param string $template_name The name of the template to render (without .php)
* @param array $attributes The PHP variables for the template
*
* @return string The contents of the template.
*/
private function get_template_html($template_name, $attributes = null) {
if (!$attributes) {
$attributes = array();
}
ob_start();
do_action('personalize_login_before_' . $template_name);
require 'templates/' . $template_name . '.php';
do_action('personalize_login_after_' . $template_name);
$html = ob_get_contents();
ob_end_clean();
return $html;
}
/**
* Redirects the user to the correct page depending on whether he / she
* is an admin or not.
*
* @param string $redirect_to An optional redirect_to URL for admin users
*/
private function redirect_logged_in_user($redirect_to = null) {
$user = wp_get_current_user();
if (user_can($user, 'manage_options')) {
if ($redirect_to) {
die($redirect_to);
wp_safe_redirect($redirect_to);
} else {
wp_redirect(admin_url());
}
} else {
wp_redirect(home_url('member-account'));
}
}
/**
* Finds and returns a matching error message for the given error code.
*
* @param string $error_code The error code to look up.
*
* @return string An error message.
*/
private function get_error_message($error_code) {
switch ($error_code) {
case 'empty_username':
return __('You do have an email address, right?', 'personalize-login');
case 'empty_password':
return __('You need to enter a password to login.', 'personalize-login');
case 'invalid_username':
return __(
"We don't have any users with that email address. Maybe you used a different one when signing up?",
'personalize-login'
);
case 'incorrect_password':
$err = __(
"The password you entered wasn't quite right. <a href='%s'>Did you forget your password</a>?",
'personalize-login'
);
// Registration errors
case 'email':
return __( 'The email address you entered is not valid.', 'personalize-login' );
case 'email_exists':
return __( 'An account exists with this email address.', 'personalize-login' );
case 'closed':
return __( 'Registering new users is currently not allowed.', 'personalize-login' );
return sprintf($err, wp_lostpassword_url());
case 'captcha':
return __( 'The Google reCAPTCHA check failed. Are you a robot?', 'personalize-login' );
default:
break;
}
return __('An unknown error occurred. Please try again later.', 'personalize-login');
}
/**
* A shortcode for rendering the new user registration form
*
* @param array $attributes Shortcode attributes.
* @param string $content The text content for shortcode. Not used.
*
* @return string The shortcode output
*/
public function render_register_form($attributes, $content = null) {
$default_attributes = array( 'show_title' => false );
$attributes = shortcode_atts( $default_attributes, $attributes );
$attributes['errors'] = [];
if(isset($_REQUEST['register-errors'])) {
$error_codes = explode(',', $_REQUEST['register-errors']);
foreach($error_codes as $code) {
$attributes['errors'][] = $this->get_error_message($error_code);
}
}
// Retrieve recaptcha key
$attributes['recaptcha_site_key'] = get_option( 'personalize-login-recaptcha-site-key', null );
if ( is_user_logged_in() ) {
return __( 'You are already signed in.', 'personalize-login' );
} elseif ( ! get_option( 'users_can_register' ) ) {
return __( 'Registering new users is currently not allowed.', 'personalize-login' );
} else {
return $this->get_template_html( 'register_form', $attributes );
}
}
/**
* Redirects the user to the custom registration page instead
* of wp-login.php?action=register.
*/
public function redirect_to_custom_register() {
if ( 'GET' == $_SERVER['REQUEST_METHOD'] ) {
if ( is_user_logged_in() ) {
$this->redirect_logged_in_user();
} else {
wp_redirect( home_url( 'member-register' ) );
}
exit;
}
}
/**
* Validates and then completes the new user signup process if all went well.
*
* @param string $email The new user's email address
* @param string $first_name The new user's first name
* @param string $last_name The new user's last name
*
* @return int|WP_Error The id of the user that was created, or error if failed.
*/
private function register_user( $email, $first_name, $last_name ) {
$errors = new WP_Error();
// Email address is used as both username and email. It is also the only
// parameter we need to validate
if ( ! is_email( $email ) ) {
$errors->add( 'email', $this->get_error_message( 'email' ) );
return $errors;
}
if ( username_exists( $email ) || email_exists( $email ) ) {
$errors->add( 'email_exists', $this->get_error_message( 'email_exists') );
return $errors;
}
// Generate the password so that the subscriber will have to check email...
$password = wp_generate_password( 12, false );
$user_data = array(
'user_login' => $email,
'user_email' => $email,
'user_pass' => $password,
'first_name' => $first_name,
'last_name' => $last_name,
'nickname' => $first_name,
);
$user_id = wp_insert_user( $user_data );
wp_new_user_notification( $user_id, $password );
return $user_id;
}
/**
* Handles the registration of a new user.
*
* Used through the action hook "login_form_register" activated on wp-login.php
* when accessed through the registration action.
*/
public function do_register_user() {
if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
$redirect_url = home_url( 'member-register' );
if ( ! get_option( 'users_can_register' ) ) {
// Registration closed, display error
$redirect_url = add_query_arg( 'register-errors', 'closed', $redirect_url );
} else {
$email = $_POST['email'];
$first_name = sanitize_text_field( $_POST['first_name'] );
$last_name = sanitize_text_field( $_POST['last_name'] );
$result = $this->register_user( $email, $first_name, $last_name );
if ( is_wp_error( $result ) ) {
// Parse errors into a string and append as parameter to redirect
$errors = join( ',', $result->get_error_codes() );
$redirect_url = add_query_arg( 'register-errors', $errors, $redirect_url );
// http://localhost/reset3/member-register/?register-errors=email
} else {
// Success, redirect to login page.
$redirect_url = home_url( 'member-login' );
$redirect_url = add_query_arg( 'registered', $email, $redirect_url );
// http://localhost/reset3/member-login/?registered=phamngoctuong5@gmail.com
}
}
wp_redirect( $redirect_url );
exit;
}
}
/**
* Registers the settings fields needed by the plugin.
*/
public function register_settings_fields() {
// Create settings fields for the two keys used by reCAPTCHA
register_setting( 'general', 'personalize-login-recaptcha-site-key' );
register_setting( 'general', 'personalize-login-recaptcha-secret-key' );
add_settings_field(
'personalize-login-recaptcha-site-key',
'<label for="personalize-login-recaptcha-site-key">' . __( 'reCAPTCHA site key' , 'personalize-login' ) . '</label>',
array( $this, 'render_recaptcha_site_key_field' ),
'general'
);
add_settings_field(
'personalize-login-recaptcha-secret-key',
'<label for="personalize-login-recaptcha-secret-key">' . __( 'reCAPTCHA secret key' , 'personalize-login' ) . '</label>',
array( $this, 'render_recaptcha_secret_key_field' ),
'general'
);
}
public function render_recaptcha_site_key_field() {
$value = get_option( 'personalize-login-recaptcha-site-key', '' );
echo '<input type="text" id="personalize-login-recaptcha-site-key" name="personalize-login-recaptcha-site-key" value="' . esc_attr( $value ) . '" />';
}
public function render_recaptcha_secret_key_field() {
$value = get_option( 'personalize-login-recaptcha-secret-key', '' );
echo '<input type="text" id="personalize-login-recaptcha-secret-key" name="personalize-login-recaptcha-secret-key" value="' . esc_attr( $value ) . '" />';
}
/**
* An action function used to include the reCAPTCHA JavaScript file
* at the end of the page.
*/
public function add_captcha_js_to_footer() {
echo "<script src='https://www.google.com/recaptcha/api.js'></script>";
}
/**
* Checks that the reCAPTCHA parameter sent with the registration
* request is valid.
*
* @return bool True if the CAPTCHA is OK, otherwise false.
*/
function handle_register_request() {
if ( ! get_option( 'users_can_register' ) ) {
// Registration closed, display error
$redirect_url = add_query_arg( 'register-errors', 'closed', $redirect_url );
} elseif ( ! $this->verify_recaptcha() ) {
// Recaptcha check failed, display error
$redirect_url = add_query_arg( 'register-errors', 'captcha', $redirect_url );
} else {
$email = $_POST['email'];
$first_name = sanitize_text_field( $_POST['first_name'] );
$last_name = sanitize_text_field( $_POST['last_name'] );
$result = $this->register_user( $email, $first_name, $last_name );
if ( is_wp_error( $result ) ) {
// Parse errors into a string and append as parameter to redirect
$errors = join( ',', $result->get_error_codes() );
$redirect_url = add_query_arg( 'register-errors', $errors, $redirect_url );
} else {
// Success, redirect to login page.
$redirect_url = home_url( 'member-login' );
$redirect_url = add_query_arg( 'registered', $email, $redirect_url );
}
}
}
private function verify_recaptcha() {
// This field is set by the recaptcha widget if check is successful
if ( isset ( $_POST['g-recaptcha-response'] ) ) {
$captcha_response = $_POST['g-recaptcha-response'];
} else {
return false;
}
// Verify the captcha response from Google
$response = wp_remote_post(
'https://www.google.com/recaptcha/api/siteverify',
array(
'body' => array(
'secret' => get_option( 'personalize-login-recaptcha-secret-key' ),
'response' => $captcha_response
)
)
);
$success = false;
if ( $response && is_array( $response ) ) {
$decoded_response = json_decode( $response['body'] );
$success = $decoded_response->success;
}
return $success;
}
}
// Initialize the plugin
$personalize_login_pages_plugin = new Personalize_Login_Plugin();
// Create the custom pages at plugin activation
register_activation_hook(__FILE__, array('Personalize_Login_Plugin', 'plugin_activated'));
C:\xampp\htdocs\reset3\wp-content\plugins\personalize-login\templates\register_form.php
<div id="register-form" class="widecolumn">
<?php if ( $attributes['show_title'] ) : ?>
<h3><?php _e( 'Register', 'personalize-login' ); ?></h3>
<?php endif; ?>
<form id="signupform" action="<?php echo wp_registration_url(); ?>" method="post">
<p class="form-row">
<label for="email"><?php _e( 'Email', 'personalize-login' ); ?> <strong>*</strong></label>
<input type="text" name="email" id="email">
</p>
<p class="form-row">
<label for="first_name"><?php _e( 'First name', 'personalize-login' ); ?></label>
<input type="text" name="first_name" id="first-name">
</p>
<p class="form-row">
<label for="last_name"><?php _e( 'Last name', 'personalize-login' ); ?></label>
<input type="text" name="last_name" id="last-name">
</p>
<p class="form-row">
<?php _e( 'Note: Your password will be generated automatically and sent to your email address.', 'personalize-login' ); ?>
</p>
<?php if ( $attributes['recaptcha_site_key'] ) : ?>
<div class="recaptcha-container">
<div class="g-recaptcha" data-sitekey="<?php echo $attributes['recaptcha_site_key']; ?>"></div>
</div>
<?php endif; ?>
<p class="signup-submit">
<input type="submit" name="submit" class="register-button" value="<?php _e( 'Register', 'personalize-login' ); ?>"/>
</p>
</form>
</div>
<?php if ( count( $attributes['errors'] ) > 0 ) : ?>
<?php foreach ( $attributes['errors'] as $error ) : ?>
<p>
<?php echo $error; ?>
</p>
<?php endforeach; ?>
<?php endif; ?>
<?php if ( $attributes['registered'] ) : ?>
<p class="login-info">
<?php
printf(__( 'You have successfully registered to <strong>%s</strong>. We have emailed your password to the email address you entered.', 'personalize-login' ),get_bloginfo( 'name' ));
?>
</p>
<?php endif; ?>
Previouscách viết lại đường dẫn đăng ký, resgister (ok)NextBuild a Custom WordPress User Flow — Part 3: Password Reset (ok)
Last updated
Was this helpful?