0
votes

So I created my own PHP CAPTCHA, this is my method of creating it:

I have a table in my database named 'Captchas' and in that table, I have two categories: ID and Captcha.

On the Captcha page this is how I set it up:

$record = mysql_query("SELECT * FROM captchas ORDER BY rand() LIMIT 1");
while($row=mysql_fetch_array($record)){

$captcha = $row['captcha'];

echo $captcha;

}

Then I have a form with two inputs, text and submit

I have the following code for the form:

echo "<form method='POST'>";
if(isset($_POST['submit'])){
$input_captcha = $_POST['input_captcha'];

if($input_captcha == $captcha){

echo "<p>Correct Captcha.</p>";

} else {


echo "<p>Incorrect Captcha.</p>";

}

}
echo "<input type='text' name='input_captcha'/>";
echo "<input type='submit' name='submit'/>";
echo "</form>";
}

What this code does is checks if the user's input is equal to the captcha so it echos 'correct captcha' and if not, 'incorrect catpcha'. Though, the problem is that it checks if the inputted text is equal to the NEXT captcha number in the randomized array. I have no idea why this is happening?

2
Store the current captcha, when you first load the page, in a session variable then check against that on submission. - chris85

2 Answers

0
votes

What I think is happening is that it is reloading the variable captcha when you try to check the user input. First make it so that instead of saving as a local variable, make it save as a session variable. Then try making the captcha generator a function and have it only called when the session variable for the captcha is not set, therefore stopping it from overwriting your variable for use at a later time.

This is how it would go:

  1. Is the captcha variable set? Yes or No: No (we just loaded the page so nothing is set)
  2. Proceed to generate a new captcha session variable
  3. Now when we check for user input against the captcha, it will try and regenerate but it will ask if the session variable is already set first. It will find out that it is in fact already set and not generate again.

That should then result in you comparing against the same two variables.

0
votes

Instead of storing the captcha code into system variable store it in session variable and then check it since by submiting the form the page is again reloaded and thus changes/replace the value of the previous captcha with new one.

Hope this might help