Skip to content

Instantly share code, notes, and snippets.

@bepatrickdavid
Last active February 15, 2023 08:04
Show Gist options
  • Save bepatrickdavid/66abc3501af0ea9f2cdf7ef6b22a2491 to your computer and use it in GitHub Desktop.
Save bepatrickdavid/66abc3501af0ea9f2cdf7ef6b22a2491 to your computer and use it in GitHub Desktop.
Simple Captcha Login WordPress
//CAPTCHA
// function number to word
function number_to_word($number) {
$words = array(
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen',
'twenty', 30 => 'thirty', 40 => 'forty', 50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 80 => 'eighty', 90 => 'ninety'
);
if(!is_numeric($number)) {
return false;
}
if(($number >= 0 && $number <= 20) || $number == 30 || $number == 40 || $number == 50 || $number == 60 || $number == 70 || $number == 80 || $number == 90) {
return $words[$number];
}
if($number > 20 && $number < 100) {
$tens = (int)($number / 10) * 10;
$ones = $number % 10;
return $words[$tens] . '-' . $words[$ones];
}
return false;
}
// add formula captcha to login page
function add_formula_captcha() {
// generate two random numbers between 0 and 10 and store them in the session
session_start();
$num1 = rand(0, 10);
$num2 = rand(0, 10);
$_SESSION['formula_captcha'] = $num1 + $num2;
// output the captcha to the login page
echo '<p>Please enter the answer to <strong>' . $num1 . ' + ' . number_to_word($num2) . '</strong>: <input type="text" name="formula_captcha" /></p>';
}
// validate formula captcha on login
function validate_formula_captcha($user, $username, $password) {
// check if the formula captcha matches the user input
session_start();
$formula_captcha = $_SESSION['formula_captcha'];
$user_captcha = $_POST['formula_captcha'];
if ($user_captcha != $formula_captcha) {
// if the captcha doesn't match, prevent the login and display an error message
remove_action('authenticate', 'wp_authenticate_username_password', 20);
return new WP_Error('invalid_captcha', 'Invalid formula captcha.');
}
return $user;
}
add_action('login_form', 'add_formula_captcha');
add_filter('authenticate', 'validate_formula_captcha', 30, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment