1

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.

6
  • I encrypted the captcha string: $captchanumber put it in a session. Then if the client enters it, the posted captcha number gets encrypted on server side and gets compared with the session. Commented Sep 25, 2014 at 9:36
  • You seem to be mixing Javascript and PHP code. You cannot do that. Commented Sep 25, 2014 at 9:36
  • You can't use PHP variables ($_SESSION and $_POST) in Javascript. Commented Sep 25, 2014 at 9:36
  • Hi Stijn Bernards, could you write the code for me? That would help me understand your point more easily. Commented Sep 25, 2014 at 9:41
  • @KIKOSoftware: may I have a Solution plz.. Commented Sep 25, 2014 at 9:43

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I am so sorry... This all went over my head.. You said, its easier to do the check in PHP.. Can you give an example for that..?
I added the PHP example.
0

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>

2 Comments

Sorry, but this will put your captcha code directly in the HTML source code. So, it might work, but is easy to circumvent.
If you don't want the captcha to be in HTML source code better to use php for comparing sessions value and posted captcha value. Or you have one better way what you can do is "Submit the form" and check both variables value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.