-1

I've read all the posts at stackoverflow and wordpress stackexchange, and none of the topics on using Google reCaptcha 2 have given me information on how to validate reCaptcha on both custom wordpress registration and login forms. I've successfully added the reCaptcha code to the page, but don't know how to implement validation. Can someone please provide some assistance?

This post here at wordpress stackexchange provides no solution other than to use a plugin: Custom ReCaptcha Login I'd prefer to not use a plugin.

Login Form:

<?php 

// for reset password section
if( isset($_GET['action']) && $_GET['action'] == 'reset_pass' ){

    list($rp_path) = explode('?', wp_unslash( $_SERVER['REQUEST_URI'] ));
    $rp_cookie = 'wp-resetpass-' . COOKIEHASH;
    if( isset($_GET['key']) ){
        $value = sprintf( '%s:%s', wp_unslash($_GET['login']), wp_unslash($_GET['key']) );
        setcookie($rp_cookie, $value, 0, $rp_path, COOKIE_DOMAIN, is_ssl(), true);
        wp_safe_redirect(remove_query_arg(array('key')));
        exit;
    }

    if( isset($_COOKIE[$rp_cookie]) && 0 < strpos( $_COOKIE[$rp_cookie], ':' ) ) {
        list($rp_login, $rp_key) = explode( ':', wp_unslash( $_COOKIE[ $rp_cookie ] ), 2 );
        $user = check_password_reset_key( $rp_key, $rp_login );
    }else{
        $user = false;
    }

    if( !$user || is_wp_error($user) ){
        setcookie($rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true);
        $args = array('login'=>home_url(), 'action'=>'lost_password');

        if ( $user && $user->get_error_code() === 'expired_key' )
            $args['status'] = 'expiredkey';
        else
            $args['status'] = 'invalidkey';

        wp_redirect(esc_url(add_query_arg($args, home_url()))); 
        exit;
    }

    $rp_errors = new WP_Error();
    if( isset($_POST['pass1']) && $_POST['pass1'] != $_POST['pass2'] ){
        $rp_errors->add('password_reset_mismatch', __('The passwords do not match.', 'gdlr-lms'));
    }

    do_action( 'validate_password_reset', $rp_errors, $user );

    if( (!$rp_errors->get_error_code()) && isset($_POST['pass1']) && !empty($_POST['pass1']) ){
        reset_password($user, $_POST['pass1']);
        setcookie( $rp_cookie, ' ', time() - YEAR_IN_SECONDS, $rp_path, COOKIE_DOMAIN, is_ssl(), true );

        wp_redirect(esc_url(add_query_arg(array('login'=>home_url(), 'status'=>'rp_complete'), home_url())));   
        exit();
    }

}

get_header(); ?>
<div id="primary" class="content-area gdlr-lms-primary-wrapper">
<div id="content" class="site-content" role="main">
<?php
    if( function_exists('gdlr_lms_get_header') && !empty($gdlr_lms_option['show-header']) && $gdlr_lms_option['show-header'] == 'enable' ){
        gdlr_lms_get_header();
    }
?>
    <div class="gdlr-lms-content">
        <div class="gdlr-lms-container gdlr-lms-container">
            <div class="gdlr-lms-item"> 

<!-- lost password form -->         
<?php if( isset($_GET['action']) && $_GET['action'] == 'lost_password' ){ ?>
    <?php
        if( empty($_GET['status']) ){
            echo '<div class="gdlr-lms-success">';
            _e('Please enter your username or email address. You will receive a link to create a new password via email.', 'gdlr-lms');
            echo '</div>';
        }else{
            echo '<div class="gdlr-lms-error">';
            if( $_GET['status'] == 'no_password_reset' ){
                _e('Password reset is not allowed for this user', 'gdlr-lms');
            }else if( $_GET['status'] == 'expiredkey' ){
                _e('Sorry, that key has expired. Please try again.', 'gdlr-lms');
            }else if( $_GET['status'] == 'invalidkey' ){
                _e('Sorry, that key does not appear to be valid.', 'gdlr-lms');
            }else{
                _e('Invalid username or e-mail.', 'gdlr-lms');
            }
            echo '</div>';
        }
    ?>

    <form name="lostpasswordform" class="gdlr-lms-form" action="<?php echo esc_url( network_site_url( 'wp-login.php?action=lostpassword', 'login_post' ) ); ?>" method="post">
        <p class="gdlr-lms-half-left">
            <label><?php _e('Username or E-mail:') ?></label>
            <input type="text" name="user_login" class="input" value="<?php echo esc_attr($user_login); ?>" size="20" />
        </p>
        <div class="clear"></div>
        <?php do_action( 'lostpassword_form' ); ?>
        <div class="clear"></div>
        <p>
            <input type="hidden" name="login" value="<?php echo $_GET['login']; ?>" />
            <input type="submit" class="gdlr-lms-button" value="<?php _e('Get New Password', 'gdlr-lms'); ?>" />
        </p>
    </form>

<!-- reset password form -->        
<?php }else if( isset($_GET['action']) && $_GET['action'] == 'reset_pass' ){ 
    if( is_wp_error($rp_errors) && $rp_errors->get_error_code() ){
        echo '<div class="gdlr-lms-error">';
        echo $rp_errors->get_error_message();
        echo '</div>';
    }
?>

<form class="gdlr-lms-form" method="post" >
    <p>
        <?php _e('<strong>Hint:</strong> The password should be at least seven characters long. To make it stronger, use upper and lower case letters, numbers, and symbols like ! " ? $ % ^ &amp; ).', 'gdlr-lms'); ?>
    </p>
    <p class="gdlr-lms-half-left">
        <label for="pass1"><?php _e('New password') ?></label>
        <input type="password" name="pass1" value="" autocomplete="off" />
    </p>
    <p class="gdlr-lms-half-right">
        <label for="pass2"><?php _e('Confirm new password') ?></label>
        <input type="password" name="pass2" value="" autocomplete="off" />
    </p>

    <div class="clear" ></div>

    <?php do_action( 'resetpass_form', $user ); ?>
    <p>
        <input type="submit" class="gdlr-lms-button" value="<?php _e('Reset Password', 'gdlr-lms'); ?>" />
    </p>
</form>

<!-- login form --> 
<?php }else{ ?>
    <?php if(!empty($_GET['status']) && $_GET['status'] == 'login_incorrect'){ ?>
        <div class="gdlr-lms-error">
        <?php _e('The login credentials is incorrect. Please try again.', 'gdlr-lms'); ?>
        </div>
    <?php }else if(!empty($_GET['status']) && $_GET['status'] == 'forgot_password_confimation'){ ?>
        <div class="gdlr-lms-success">
        <?php _e('Please check your e-mail for the confirmation link.', 'gdlr-lms'); ?>
        </div>
    <?php }else if(!empty($_GET['status']) && $_GET['status'] == 'rp_complete'){ ?>
        <div class="gdlr-lms-success">
        <?php _e('Your password has been reset.', 'gdlr-lms'); ?>
        </div>
    <?php } ?>

    <form class="gdlr-lms-form" id="loginform" method="post" action="<?php echo esc_url(site_url('wp-login.php', 'login_post')); ?>">


        <p class="gdlr-lms-half-left">
            <label><?php _e('Username', 'gdlr-lms'); ?></label>
            <input type="text" name="log" />
        </p>
        <p class="gdlr-lms-half-right">
             <label><?php _e('Password', 'gdlr-lms'); ?></label>
             <input type="password" name="pwd" />
        </p>
        <div class="clear"></div>
        <?php //o_action( 'login_form' ); ?>
        <p class="gdlr-lms-lost-password" >
            <?php $login_url = empty($_GET['login'])? home_url(): $_GET['login']; ?>
            <a href="<?php echo wp_lostpassword_url($login_url); ?>" ><?php _e('Lost Your Password?','gdlr-lms'); ?></a>
        </p>

        <div class="clear"></div>
        <script src='https://www.google.com/recaptcha/api.js'></script>
        <div class="g-recaptcha" data-sitekey="123456789012345678901234567890_"></div>
        <div class="clear"></div>

        <p>
            <input type="hidden" name="home_url"  value="<?php echo home_url(); ?>" />
            <input type="hidden" name="rememberme"  value="forever" />
            <input type="hidden" name="redirect_to" value="<?php echo $_GET['login'] ?>" />
            <input type="submit" name="wp-submit" class="gdlr-lms-button" value="<?php _e('Sign In!', 'gdlr-lms'); ?>" />
        </p>

        <?php
        /*
        //if(isset($_POST['g-recaptcha-response'])){
            $captcha=$_POST['g-recaptcha-response'];
            $g_response = json_decode($response);
            $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=123456789012345678901234567890&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);

            if($g_response->success===true) {
                echo "<div style='float: right; opacity: 0.08;'>success</div>";
            } else {
                echo "<div style='float: right; opacity: 0.08;'>No Success</div>";
            }
        //}
        */
        ?>
    </form>
<?php } ?>
            </div>
        </div>
    </div>
</div>
</div>
<?php
if( !empty($gdlr_lms_option['show-sidebar']) && $gdlr_lms_option['show-sidebar'] == 'enable' ){ 
    get_sidebar( 'content' );
    get_sidebar();
}

get_footer(); ?>

Registration Form:

<?php 
    $error = array();
    if( !empty($_POST['action']) && $_POST['action'] == 'create-new-user' ){
        if( empty($_POST['username']) || empty($_POST['password']) || empty($_POST['re-password']) || 
            empty($_POST['first_name']) || empty($_POST['last_name']) || empty($_POST['gender']) || 
            empty($_POST['birth_date']) || empty($_POST['email']) || empty($_POST['address']) ){

            $error[] = __('Please enter all required fields.', 'gdlr-lms');
        }

        if( $_POST['password'] != $_POST['re-password'] ){
            $error[] = __('Password and password confirmation do not match.', 'gdlr-lms');
        }

        if( username_exists($_POST['username']) ){
            $_POST['username'] = '';
            $error[] = __('Username already exists, please try again with another name.', 'gdlr-lms');
        }

        if( email_exists($_POST['email']) ){
            $_POST['email'] = '';
            $error[] = __('Email already exists, Please try again with new email address.', 'gdlr-lms');
        }

        if( !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ){
            $_POST['email'] = '';
            $error[] = __('Email is not valid.', 'gdlr-lms');
        }

        if( empty($error) ){
            $user_id = wp_insert_user(array(
                'user_login' => $_POST['username'], 
                'user_pass' => $_POST['password'], 
                'user_email' => $_POST['email'],
                'role' => 'student'
            ));

            if( is_wp_error($user_id) ){
                $error[] = __('Please only fill latin characters in username and password fields.', 'gdlr-lms');
            }else{
                if( !empty($_POST['first_name']) ){
                    update_user_meta($user_id, 'first_name', esc_attr($_POST['first_name']));
                }
                if( !empty($_POST['last_name']) ){
                    update_user_meta($user_id, 'last_name', esc_attr($_POST['last_name']));
                }
                if( !empty($_POST['gender']) ){
                    update_user_meta($user_id, 'gender', esc_attr($_POST['gender']));
                }
                if( !empty($_POST['birth_date']) ){
                    update_user_meta($user_id, 'birth-date', esc_attr($_POST['birth_date']));
                }
                if( !empty($_POST['phone']) ){
                    update_user_meta($user_id, 'phone', esc_attr($_POST['phone']));
                }
                if( !empty($_POST['dcjs']) ){
                    update_user_meta($user_id, 'dcjs', $_POST['dcjs']);
                }   
                if( !empty($_POST['address']) ){
                    update_user_meta($user_id, 'address', $_POST['address']);
                }   
                wp_new_user_notification($user_id, $_POST['password']);

                $redirect_url = empty($_GET['register'])? home_url(): $_GET['register'];
                // $redirect = esc_url(add_query_arg('login', $redirect_url, home_url())); 
                // wp_redirect($redirect);
                // exit;

?>
<form method="post" action="<?php echo esc_url(site_url('wp-login.php', 'login_post')); ?>" id="login-redirect">
    <input type="hidden" name="log" value="<?php echo $_POST['username']; ?>" />
    <input type="hidden" name="pwd" value="<?php echo $_POST['password']; ?>" />
    <input type="hidden" name="rememberme"  value="forever" />
    <input type="hidden" name="redirect_to" value="<?php echo $redirect_url; ?>" />
</form>

<script type="text/javascript">
   document.getElementById("login-redirect").submit();
</script>
<?php               

            }
        }
    }
    get_header(); 
?>
<div id="primary" class="content-area gdlr-lms-primary-wrapper">
<div id="content" class="site-content" role="main">
<?php
    if( function_exists('gdlr_lms_get_header') && !empty($gdlr_lms_option['show-header']) && $gdlr_lms_option['show-header'] == 'enable' ){
        gdlr_lms_get_header();
    }
?>


    <div class="gdlr-lms-content">
        <div class="gdlr-lms-container gdlr-lms-container">
            <div class="gdlr-lms-item">
                <?php
                    if( !empty($error) ){
                        echo '<div class="gdlr-lms-error">' . implode("<br />", $error) . '</div>'; 
                    }       
                ?>
                <form class="gdlr-lms-form" method="post" action="">
                    <p class="gdlr-lms-half-left">
                        <label><?php _e('Username *', 'gdlr-lms'); ?></label>
                        <input type="text" name="username" value="<?php echo isset($_POST['username'])? $_POST['username']: ''; ?>" />
                    </p>
                    <div class="clear"></div>
                    <p class="gdlr-lms-half-left">
                        <label><?php _e('Password *', 'gdlr-lms'); ?></label>
                        <input type="password" name="password" />
                    </p>
                    <p class="gdlr-lms-half-right">
                         <label><?php _e('Re Password *', 'gdlr-lms'); ?></label>
                         <input type="password" name="re-password" />
                    </p>
                    <div class="clear"></div>
                    <p class="gdlr-lms-half-left">
                        <label><?php _e('First Name *', 'gdlr-lms'); ?></label>
                        <input type="text" name="first_name" value="<?php echo isset($_POST['first_name'])? $_POST['first_name']: ''; ?>" />
                    </p>
                    <p class="gdlr-lms-half-right">
                         <label><?php _e('Last Name *', 'gdlr-lms'); ?></label>
                         <input type="text" name="last_name" value="<?php echo isset($_POST['last_name'])? $_POST['last_name']: ''; ?>" />
                    </p>
                    <div class="clear"></div>       
                    <p class="gdlr-lms-half-left">
                        <label><?php _e('Gender *', 'gdlr-lms'); ?></label>
                        <span class="gdlr-lms-combobox">
                            <select name="gender" id="gender" >
                                <option value="m" <?php if(isset($_POST['gender']) && $_POST['gender'] == 'm') echo 'selected'; ?> ><?php _e('Male', 'gdlr-lms'); ?></option>
                                <option value="f" <?php if(isset($_POST['gender']) && $_POST['gender'] == 'f') echo 'selected'; ?> ><?php _e('Female', 'gdlr-lms'); ?></option>
                            </select>
                        </span>                 
                    </p>
                    <p class="gdlr-lms-half-right">
                         <label><?php _e('Birth Date *', 'gdlr-lms'); ?></label>
                         <input type="text" name="birth_date" value="<?php echo isset($_POST['birth_date'])? $_POST['birth_date']: ''; ?>" />
                    </p>
                    <div class="clear"></div>       
                    <p class="gdlr-lms-half-left">
                        <label><?php _e('Email *', 'gdlr-lms'); ?></label>
                        <input type="text" name="email" id="email" value="<?php echo isset($_POST['email'])? $_POST['email']: ''; ?>" />
                    </p>
                    <p class="gdlr-lms-half-right">
                        <label><?php _e('DCJS *', 'gdlr-lms'); ?></label>
                        <input type="text" name="dcjs" id="dcjs"  value="<?php echo isset($_POST['dcjs'])? $_POST['dcjs']: ''; ?>" />
                    </p>
                    <div class="clear"></div>
                    <p class="gdlr-lms-half-left">
                        <label><?php _e('Phone', 'gdlr-lms'); ?></label>
                        <input type="text" name="phone" id="phone" value="<?php echo isset($_POST['phone'])? $_POST['phone']: ''; ?>" />
                    </p>

                    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.7/jquery.inputmask.bundle.min.js"></script>

                    <script type="text/javascript">
                    jQuery(document).ready(function(){

                        // $("#dcjs").inputmask();
                        jQuery("#dcjs").inputmask(

                        'decimal',{
                            autoGroup: true,
                            groupSeparator: "",
                            allowPlus: false,
                            allowMinus: false,
                            prefix: "99-",
                            suffix: "",
                            digits:6,
                            placeholder:'',
                            repeat: 6,  greedy : false,
                            rightAlign: false,
                            keepStatic: true
                        }

                        /* {prefix: "99-",'mask':"9{0,6}", greedy: false}*/
                        // 'Regex', { prefix:'99-',regex: "^[9-9]{2,2}[/\-][0-9]{4,6}$", showMaskOnHover: true }
                        ); 
                    });

                    </script>
                    <p class="gdlr-lms-half-right">
                        <label><?php _e('Address *', 'gdlr-lms'); ?></label>
                        <textarea name="address" id="address" ><?php echo isset($_POST['address'])? esc_textarea($_POST['address']): ''; ?></textarea>
                    </p>

                    <div class="clear"></div>
                    <script src='https://www.google.com/recaptcha/api.js'></script>
                    <div class="g-recaptcha" data-sitekey="123456789012345678901234567890_"></div>
                    <div class="clear"></div>

                    <p>
                        <input type="hidden" name="action" value="create-new-user" />
                        <input type="submit" class="gdlr-lms-button" value="<?php _e('Create an account', 'gdlr-lms'); ?>" />
                    </p>
                </form>
            </div>
        </div>
    </div>
</div>
</div>
<?php 
if( !empty($gdlr_lms_option['show-sidebar']) && $gdlr_lms_option['show-sidebar'] == 'enable' ){ 
    get_sidebar( 'content' );
    get_sidebar();
}

get_footer(); ?>

1 Answer 1

0

First connect the CAPTCHA script (add to: functions.php)

function onwp_enqueue_frontend() {
wp_enqueue_script('ha-recaptcha', 'https://www.google.com/recaptcha/api.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'onwp_enqueue_frontend');

In the form of adding the following html code to display the captcha

<div class="g-recaptcha" data-sitekey="YOU_SITE_CODE"></div>

YOU_SITE_CODE - replaced by your code

Next, add the CAPTCHA validation feature

$recaptcha = $_POST['data']['g_recaptcha_response'];
 if (!empty($recaptcha)) {
 $google_url = "https://www.google.com/recaptcha/api/siteverify";
 $secret = 'YOU_SECRET_CODE';
 $ip = $_SERVER['REMOTE_ADDR'];
 $url = $google_url . "?secret=" . $secret . "&response=" . $recaptcha . "&remoteip=" . $ip;
 $res = onwp_getCurlData($url);
 $res = json_decode($res, true);
 //reCaptcha введена
 if (empty($res['success'])) {
 // Error, please enter the captcha again
 } else {
// all passed successfully perform your actions
}
 } else {
 // Error, please enter the captcha again
 }

YOU_SECRET_CODE - replaced by your code

Function executes the query(add to functions.php):

function onwp_getCurlData($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
$curlData = curl_exec($curl);
curl_close($curl);
return $curlData;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.