Saturday, 7 September 2019

Make Captcha Script in PHP with Ajax



This post will explain you, how to make your own custom captcha in PHP using jQuery and Ajax in HTML form.

Do you know what is captcha. In web development, Captcha is one random generated alpha numeric captcha string, and it is stored in session variable for validate it with the captcha code enter by the user at the time of filling of form field.

Captacha is for prevent the bot or spammer for filling form field automatically. Because Captcha code has been display in an image, which can be only human can able to read it.

When we have allow public user to enter data into our website, then we need to identify that data has been enter by human. Because currently, many people has use robots to fill form data, so many unwanted data has been entered into website. So it will increase lots of load on our website, which will be down for sometime.

So, Captcha is one type of methods which helps website owner to prevent robots or bots from inserting of data. There are different type of Captcha like text-based, audio based or image based we can implement our web page, and it will generate random code dynamically. In form filling captcha code will be mandatory, without filling code user cannot submit form, so robot cannot read image text and robot will not submit form with data.

In this post, we will use PHP script for image with dynamic alpha numeric string and make graphics based captcha code. Here Captcha code will be stored under PHP $_SESSION variable for future use.And for validate user has enter correct captcha code, for this we will use jQuery and Ajax.







Source Code


index.php



<?php

//index.php

?>

<html>  
    <head>  
        <title>How to implement Custom Captcha Code in PHP</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container" style="width: 600px">
   <br />
   
   <h3 align="center">How to implement Custom Captcha Code in PHP</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Register Form</div>
    <div class="panel-body">
     <form method="post" id="captch_form">
      <div class="form-group">
       <div class="row">
        <div class="col-md-6">
         <label>First Name</label>
         <input type="text" name="first_name" id="first_name" class="form-control" />
        </div>
        <div class="col-md-6">
         <label>Last Name</label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
        </div>
       </div>
      </div>
      <div class="form-group">
       <label>Email Address</label>
       <input type="text" name="email" id="email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="password" id="password" class="form-control" />
      </div>
      <div class="form-group">
       <div class="form-group">
                          <label>Code</label>
                          <div class="input-group">
                           <input type="text" name="captcha_code" id="captcha_code" class="form-control" />
                           <span class="input-group-addon" style="padding:0">
          <img src="image.php" id="captcha_image" />
         </span>
                          </div>
                         </div>
      </div>
      <div class="form-group">
       <input type="submit" name="register" id="register" class="btn btn-info" value="Register" />
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>



<script>
 $(document).ready(function(){
  
  $('#captch_form').on('submit', function(event){
   event.preventDefault();
   if($('#captcha_code').val() == '')
   {
    alert('Enter Captcha Code');
    $('#register').attr('disabled', 'disabled');
    return false;
   }
   else
   {
    alert('Form has been validate with Captcha Code');
    $('#captch_form')[0].reset();
    $('#captcha_image').attr('src', 'image.php');
   }
  });

  $('#captcha_code').on('blur', function(){
   var code = $('#captcha_code').val();
   
   if(code == '')
   {
    alert('Enter Captcha Code');
    $('#register').attr('disabled', 'disabled');
   }
   else
   {
    $.ajax({
     url:"check_code.php",
     method:"POST",
     data:{code:code},
     success:function(data)
     {
      if(data == 'success')
      {
       $('#register').attr('disabled', false);
      }
      else
      {
       $('#register').attr('disabled', 'disabled');
       alert('Invalid Code');
      }
     }
    });
   }
  });

 });
</script>



image.php



<?php

//image.php

session_start();

$random_alpha = md5(rand());

$captcha_code = substr($random_alpha, 0, 6);

$_SESSION['captcha_code'] = $captcha_code;

header('Content-Type: image/png');

$image = imagecreatetruecolor(200, 38);

$background_color = imagecolorallocate($image, 231, 100, 18);

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

imagefilledrectangle($image, 0, 0, 200, 38, $background_color);

$font = dirname(__FILE__) . '/arial.ttf';

imagettftext($image, 20, 0, 60, 28, $text_color, $font, $captcha_code);

imagepng($image);

imagedestroy($image);

?>


check_code.php



<?php

//check_code.php

session_start();

$code = $_POST['code'];

if($code == $_SESSION['captcha_code'])
{
 echo 'success';
}

?>


14 comments:

  1. Nice, but we have to reload captcha
    (Need button to reload captcha image)

    ReplyDelete
  2. hello, my image is not showing,can u help me

    ReplyDelete
  3. your work is so great! - I've been thinking about doing a recaptcha with emoticons, where the use has to answer how many of them are happy? If this was inspiring to you I'd be happy to find a solution at your website. Just a thought.

    ReplyDelete
  4. hello , my img coming broken can you guys help me with this

    ReplyDelete
  5. your code is not working sir

    ReplyDelete
  6. if i put same data on both side it say invalid

    ReplyDelete
  7. https://www.html-code-generator.com/php/captcha-image-code-generator

    ReplyDelete
  8. Image is broken, what's the solution sirs?

    ReplyDelete
  9. hi sir, same question as ibiso the image are broken, i have code image.php doesn't work i don't know why?

    ReplyDelete
  10. it's ok for me, i just download arial.ttf

    ReplyDelete
    Replies
    1. where did u dwld it. can u plz share the link

      Delete
  11. How to download arial.ttf ? how to use it ?

    ReplyDelete