Implement Time Based Captcha on Login Form

In one of my previous post I showed how to create custom captcha to secure your WordPress login form. Today, I will also talk about Captcha as well but from a different point of view. In my previous example I showed how to generate random number and use PHP Session to validate user input. Today, I will focus on generating numbers based on server time and then validate user input against it.

The idea is fairly simple and works pretty much the same way. However, there are significant differences between these two concept as well. This method will definitely cut down the size of our function and hassles that comes with $_SESSION issue. Also, instead of generating a new number on every page refresh, it will generate new number on every 60 seconds as it is dependent on your web server's system clock. So, here we go.

<?php
// add the captcha fields to login form
function add_captcha_field() {
   $captcha = date('njhi');
   echo '<p><label for="user_catpcha">Captcha: '.$captcha.'<br>';
   echo '<input type="text" name="user_catpcha"></label></p>';}
add_action('login_form','add_captcha_field');
// authenticate the user input
function user_captcha_authenticate($user,$username,$password) {
   $time = date('njhi');
   $submission = $_POST['user_catpcha'];
   $user = get_user_by('login', $username);
      if (!$user||empty($submission)||$submission != $time) {
         remove_action('authenticate','wp_authenticate_username_password',20);
         return new WP_Error('die','<strong>ERROR</strong>: Wrong Captcha!'); }
   return; }
add_filter('authenticate','user_captcha_authenticate',10,3);	
?>

Now, all you need to do is to copy and paste this snippet on your theme's functions.php page and update it accordingly. That's all.

WordPress Login Form with Captcha
Script Generates Captcha Number Based on Current Date & Time.

Explanation:

On my "add_captcha_field" function, I declared $time variable to hold the current month, day of the month and time. I have used the default PHP date function. As the parameter, I used njhi in short that means the format should be Month, Day of the month in number, Hours and Minutes. Since only the "Minute" would change in every 60 second it would make the Captcha number unique. It also means any user would get maximum of 40-50 seconds on an average to input the captcha value. If you are bit late, most probably you won't be able to log in as the value would change by the time you enter captcha value. I hope you got the idea. Feel free to try it out and let me know if you have any question on this regard.

Related

Comments

Comments list