Wednesday, August 26, 2020

Custom captcha in wordpress and inject it to ACF front end form

 First create a file in your theme named: fcaptcha.php
fcaptcha.php

<?php 

session_start();

$permitted_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ';

function generate_string($input, $strength = 10) {

  $input_length = strlen($input);

  $random_string = '';

  for($i = 0; $i < $strength; $i++) {

      $random_character = $input[mt_rand(0, $input_length - 1)];

      $random_string .= $random_character;

  }

  return $random_string;

}

$image = imagecreatetruecolor(200, 50);

imageantialias($image, true);

$colors = []; 

$red = rand(125, 175);

$green = rand(125, 175);

$blue = rand(125, 175); 

for ( $i = 0; $i < 5; $i++ ) {

  $colors[] = imagecolorallocate($image, $red - 20*$i, $green - 20*$i, $blue - 20*$i);

}

imagefill($image, 0, 0, $colors[0]);

$black = imagecolorallocate($image, 0, 0, 0);

$white = imagecolorallocate($image, 255, 255, 255);

$textcolors = [$black, $white];

$string_length = 6;

$captcha_string = generate_string($permitted_chars, $string_length);

$_SESSION['captcha_text'] = $captcha_string;

imagestring($image, 18, 10, 12, $captcha_string, $textcolors[rand(0, 1)]);

imagepng($image);
************************************
After that, in functions.php file put the below code to start session:

if ( ! session_id() ) {
session_start();
}

And add below lines to functions.php to localize some data:

wp_enqueue_script('jsScript', get_template_directory_uri() . '/js/script.js', array('jquery'), false, true);
$translation_array = array( 'templateUrl' => get_stylesheet_directory_uri() );
wp_localize_script( 'jsScript', 'globalJSObject', $translation_array );

script.js
$('<img/>').attr({ src: globalJSObject.templateUrl+'/fcaptcha.php', id: 'captcha_image'}).appendTo('.solution_captcha');

See the class name of solution_captcha, it can be anything but you will need to put that class in your ACF captcha field.

Switch PHP version in Ubuntu OS or Zorin OS

First check where is installed your PHP by the below command: $ which php See PHP version by below command: $ php -v As I've installed P...