简体   繁体   中英

how to validate CAPTCHA using php and jquery

I am new to web development and I am trying to put CAPTCHA into my website. I am stuck at this. And I couldn't find any help.

The following is my Form code:

<tr>
    <td>
        <img src="html-contact-form-captcha/captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
    </td>
    </tr>
    <tr>
      <td align="right"><b> Enter Image Text </b></td>
      <td><input placeholder="Enter the code above here" id="6_letters_code" name="6_letters_code" type="text"><br>
          <small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
      </td>
    </tr>

And on this same page I am trying to validate this CAPTCHA by the following code:

var cde = document.getElementById('6_letters_code');
    if( cde.value == "" ||
        ($_SESSION['6_letters_code'] != $_POST['6_letters_code']) ) {

                alert( "Code Matched!" );
                //alert( "Code Doesn't Match! \n Code Not Entered!" );
                return false; 
   }

And this is where I am getting my CAPTCHA: (captcha.php)

session_start(); // Staring Session
$captchanumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz'; // Initializing PHP variable with string
$captchanumber = substr(str_shuffle($captchanumber), 0, 6); // Getting first 6 word after shuffle.
$_SESSION["code"] = $captchanumber; // Initializing session variable with above generated sub-string
$image = imagecreatefromjpeg("bj.jpg"); // Generating CAPTCHA
$foreground = imagecolorallocate($image, 175, 199, 200); // Font Color
imagestring($image, 5, 45, 8, $captchanumber, $foreground);
header('Content-type: image/png');
imagepng($image);

Any help would be appreciated.

Thank you in advance.

In Javascript

If you want to evaluate that the captcha is correct in Javascript, which runs in your browser after the page was generated by PHP on the server, then Javascript will have to have the means to check it.

For this you have to use a session, in which you can store the captcha value. Use these steps:

  1. At the start of the PHP file, that generates your form, you should select a captcha code. You store this in a session variable.

  2. You produce a hash of the captcha in PHP and put it in a hidden field of the form. Give this field a proper id, so you can find it with Javascript.

     $hash = sha1($captcha); // this is PHP code 
  3. Generate the image of the captcha, using the stored session variable.

  4. Regrettably Javascript does not have any native hash algorithm. Other people have solved this:

http://caligatio.github.io/jsSHA/

So now you can also make a hash of the captcha, that was entered by the user into the form, in Javascript. All you need to do is to check it against the hash that PHP has put in the hidden field in the form. If they match the Captcha was correct.

As you can see, this is not really easy.

In PHP

It is easier to do the check in PHP after the form was submitted. I think I can assume your captcha.php works. In that you store $captchanumber in the session of the user. That was a good idea.

So you make the form, put the captcha in it, and let the user submit it. The check will now be done in PHP, like this:

$captchaNumber = $_SESSION['code'];
$userNumber    = $_POST['6_letters_code']; // a name starting with number? eh??
if ($captchaNumber == $userNumber)
{
  <.... the user did it correctly ....>
}
else
{
  // it was the wrong code, back to the form
  header('Location: '.<... url of form ...>);
}

The header() function should be used before any output. For starters I would suggest to submit the form to another PHP script. Once that works you can try an merge the form script and the submission script into one PHP script.

Please try the below code. I hope it work. I tried to write the code from scratch:-

<?php session_start();
// Staring Session
$im = imagecreate(90, 30);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 0);

$captchaKey = substr(md5(time()), 0, 5);
$_SESSION["code"] = $captchaKey;
imagestring($im, 45, 20, 5, $captchaKey, $textcolor);

//header("Content-type: image/png");
$save = "captcha.png";
$x1 = imagepng($im, $save);
?>

<script>
    function checkCaptcha() {
var cde = document.getElementById('6_letters_code');

if( cde.value == '<?php echo $_SESSION['code']; ?>
    ' ) {

    alert( "Code Matched!" );
    //alert( "Code Doesn't Match! \n Code Not Entered!" );
    return false;
    } else {
        alert('Code not matched!')
      }
    }
</script>

<tr>
    <td><img src="captcha.png" id='captchaimg' >
    <br>
    </td>
</tr>
<tr>
    <td align="right"><b> Enter Image Text </b></td>
    <td>
    <input placeholder="Enter the code above here" id="6_letters_code" name="6_letters_code" type="text">
    <br>
    <button onclick="checkCaptcha()">
        Click to check
    </button><small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small></td>
</tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM