Create image CAPTCHA using PHP and validate using JavaScript

Create image CAPTCHA using PHP and validate using JavaScript. We all encountered such a situation when we have to enter a captcha in the form. Captcha is used to prevent spam injection on the website through your form.  So, if you use captcha in your website form, then it will become harder for any bot to get access your website form.

There are better captchas but in this tutorial, I will give you a detailed explanation of how captcha really works. Let’s follow this tutorial, where we will see how to create image CAPTCHA using PHP and validate using JavaScript. One more thing, you must have GD (Graphics Draw) installed on your server before proceeding.

Create image CAPTCHA using PHP and validate using JavaScript

Create Image CAPTCHA Using PHP

We will follow some steps to generate image captcha using PHP —

  • Create an empty image on the web.
  • Assign a shape to the image.
  • Generate four random lines.
  • Generate five hundred random dots.
  • Generate random text of five characters.

Create an empty image on the web using PHP

$image = imagecreatetruecolor(150, 50);

The imagecreatetruecolor() function from the above PHP code returns a black image of the specified size on the web and stores the reference of that image in the $image variable.

Assign a shape to the image

$image_background_color = imagecolorallocate($image, 155,155,155);
imagefilledrectangle($image, 0, 0, 150, 50, $image_background_color);

The imagefilledrectangle() function creates a rectangle based on the given points filled with the background image color.

Generate four random lines

$line_color = imagecolorallocate($image, 230, 230, 230);
for ($i = 0; $i < 4; $i++) {
    imageline($image, 0, rand() % 50, 150, rand() % 50, $line_color);
}

The imageline() draws a new line between the two points. In the above code, we used for loop, so that we can create multiple lines.

Generate five hundred random dots

$dot_color = imagecolorallocate($image, 0, 0, 255);
for ($i = 0; $i < 500; $i++) {
    imagesetpixel($image, rand() % 150, rand() % 50, $dot_color);
}

The imagesetpixel() function draws a pixel at the specified coordinate. We created here five hundred dots, you can create as many as you want.

Generate random text of five characters

$font_color = imagecolorallocate($image, 255, 255, 255);
$characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz';
$chars_len  = strlen($characters);

$captcha_string = "";
$temp_xco = 20;
for($i=0; $i<5; $i++) {
   $single_letter = $characters[rand(0, $chars_len - 1)];
   //image, font-size, angle, xco, ycon, font-color, font, captch string
   $bbox = imagettftext($image, 15, 0, $temp_xco, 33, $font_color, 'arial.ttf', $single_letter);
   $temp_xco += 15 + ($bbox[2] - $bbox[0]);
   $captcha_string .= $single_letter;
}

The above code generates a string of five random characters. The imagettftext() function writes text to the image. We can use various fonts, as I used here arial.ttf.

Generate or save the image

imagepng($image, 'captcha.png');
$_SESSION['captcha_string'] = $captcha_string;

The imagepng() function generates or saves a png image based on the image instance. At last, we will save the captcha string in the session so that we can use it later for form validation.

Complete Code For Creating Image Captcha Using PHP

Now create a captcha.php file and paste the below code into it.

<?php 
@session_start();
if(isset($_POST['getcaptchastring']) && $_POST['getcaptchastring'] == 'yes') {
    echo $_SESSION['captcha_string'];
} else {

  $image = imagecreatetruecolor(150, 50);

  $image_background_color = imagecolorallocate($image, 155,155,155);
  imagefilledrectangle($image, 0, 0, 150, 50, $image_background_color);

  $dot_color = imagecolorallocate($image, 0, 0, 255);
  for ($i = 0; $i < 500; $i++) {
        imagesetpixel($image, rand() % 150, rand() % 50, $dot_color);
    }

    $line_color = imagecolorallocate($image, 230, 230, 230);
    for ($i = 0; $i < 4; $i++) {
        imageline($image, 0, rand() % 50, 150, rand() % 50, $line_color);
    }

    $font_color = imagecolorallocate($image, 255, 255, 255);
    $characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz';
    $chars_len  = strlen($characters);


    $captcha_string = "";
    $temp_xco = 20;
    for($i=0; $i<5; $i++) {
        $single_letter = $characters[rand(0, $chars_len - 1)];
                            //image, font-size, angle, xco, ycon, font-color, font, captch string
        $bbox = imagettftext($image, 15, 0, $temp_xco, 33, $font_color, 'arial.ttf', $single_letter);
        $temp_xco += 15 + ($bbox[2] - $bbox[0]);
        $captcha_string .= $single_letter;
    }

    $_SESSION['captcha_string'] = $captcha_string;

  imagepng($image, 'captcha.png');
}
?>

HTML Form (index.php)

<?php include('captcha.php'); ?>

  <div class="container-fluid">
    <div class="row">
      <div class="col-xs-12 col-md-4"></div>
      <div class="col-xs-12 col-md-4">
        <form action="go-to-the-page-where-you-want" id="validateForm" method="post">
          <table class="table">
            <tr>
              <th colspan="3" class="tableheader">PHP IMAGE CAPTCHA WITH JAVASCRIPT VALIDATION</th>
            </tr>
            <tr>
              <th>Name</th>
              <td>:</td>
              <td><input type="text" name="name" id="name" value=""></td>
            </tr>
            <tr>
              <th>Mobile</th>
              <td>:</td>
              <td><input type="text" name="mobile" id="mobile" value=""></td>
            </tr>
            <tr>
              <th>Captcha</th>
              <td>:</td>
              <td>
                <div class="captcha_div">
                  <span class="captchabox"><img src="captcha.png"></span>
                  <img src="refresh.png" class="refresh" width="40">
                </div>
                <input type="text" name="captcha" id="captcha" value="">
              </td>
            </tr>
            <tr>
              <th>&nbsp;</th>
              <td>&nbsp;</td>
              <td><input type="button" name="submit_btn" id="submit_btn" value="Submit"></td>
            </tr>
          </table>
        </form>	
      </div><!-- cols -->
      <div class="col-xs-12 col-md-4"></div>
    </div><!-- .row -->
  </div>

At the beginning of the above code, we included the captcha.php, so that when the index file will load for the first time it will create the first captcha image and store the captcha string in the session variable.

Validate The CAPTCHA (index.php)

$(document).ready(function() {

      $('#validateForm #submit_btn').on('click', function(event) {

        event.preventDefault();
        var error = false;
        $("span.error").remove();
        var name    = $("#name").val();
        var mobile  = $("#mobile").val();
        var captcha = $("#captcha").val();

        if(name == '') {
          $('<span class="error">Please enter name.</span>').insertAfter("#name");
          error = true;
        }

        if(mobile == '') {
          $('<span class="error">Please enter mobile number.</span>').insertAfter("#mobile");
          error = true;
        }

        if(captcha == '') {
          $('<span class="error">Please enter captcha!</span>').insertAfter("#captcha");
          error = true;
        } else {
          $.post("captcha.php", {getcaptchastring : 'yes'}, function(data) {
            if(captcha != data) {
              $('<span class="error">Wrong captcha entered!</span>').insertAfter("#captcha");
              error = true;
            }
          })
          .done(function() {
            if(error === false) {
              $('#validateForm').get(0).submit();
            }
          });
        }
        
      });

    });

In the case of captcha validation, we send an HTTP POST request with plain string data to the captcha.php. captcha.php checks of any POST variable is set or not. If set then it returns only the captcha string which was stored in the session variable, else it creates a new captcha image and stores the new captcha string in the session variable.

Refresh The Captcha Image (index.php)

Another thing we introduced here that is a refresh button which will refresh the captcha image by creating new captcha image.

$('.refresh').click(function() {
   $('#captcha').val('');
   $.post("captcha.php", function(data) {
       var d = new Date();
       $('span.captchabox img').attr('src', 'captcha.png?'+d.getTime());
   });
});

To refresh the captcha image, again we will send an HTTP POST request to the captcha.php page with no data. And assign the image src value with the same name captcha.png but we will append a different time with the src so that the new image will display otherwise the existing image remains.

Download The Complete Source Code Of – Create Image Captcha Using PHP and Validate Using JavaScript

Please download the complete source code from the below download link. Also, you can try the demo from the below demo link. Please like and share this tutorial with others.

2 thoughts on “Create image CAPTCHA using PHP and validate using JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *