PHP simple math tracking function

I am trying to write a simple math captcha function to validate a form that will force users to publish a specific article on a blog.

Function:

function create_captcha($num1, $num2) { $num1 = (int)$num1; $num2 = (int)$num2; $rand_num_1 = mt_rand($num1, $num2); $rand_num_2 = mt_rand($num1, $num2); $result = $rand_num_1 + $rand_num_2; return $result; } 

the form:

 <h2 class="email_users_headers">Post Article</h1> <form action="" method="post" id="post_blog_entry"> <input type="text" name="title" id="title" placeholder="title... *"><br> <textarea name="content" id="content" cols="30" rows="5" placeholder="content... *"></textarea><br> <?php echo create_captcha(1, 20) . ' + ' . create_captcha(1, 20) . ' = '; ?> <input type="text" name="captcha_results" size="2"> <input type="hidden" name='num1' value='<?php echo create_captcha(1, 20); ?>'> <input type="hidden" name='num2' value='<?php echo create_captcha(1, 20); ?>'> <input type="submit" name="publish" value="post entry" id="publish"> </form> 

Verification Check:

 if (empty($_POST['captcha_results']) === true) { $errors[] = 'Please enter captcha'; } else { if ($_POST['captcha_results'] != $_POST['num1'] + $_POST['num2']) { $errors[] = 'Incorrect captcha'; } } 

I know this is completely wrong, because regardless of the input, the result is always incorrect. Can someone point me in the right direction since I have no experience with PHP.

+4
source share
1 answer

Each time you run create_captcha(1, 20) , it generates different values.

  • create_captcha (1, 20) - 3 + 7 = 10
  • create_captcha (1, 20) - 6 + 11 = 17 ...

And in your form you call it 4 times.

I think you should do this:

 $num1 = create_captcha(1, 20); $num2 = create_captcha(1, 20); 

And use these values ​​in your form:

 <textarea name="content" id="content" cols="30" rows="5" placeholder="content... *"></textarea><br> <?php echo $num1 . ' + ' . $num2 . ' = '; ?> <input type="text" name="captcha_results" size="2"> <input type="hidden" name='num1' value='<?php echo $num1; ?>'> <input type="hidden" name='num2' value='<?php echo $num2; ?>'> 
+2
source

All Articles