PHP简单的数学验证码功能

I am trying to write a simple math captcha function to validate a form which will alow users to post a specific article on a blog.

The 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;
    }

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>

Captcha validation:

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 totally wrong because no matter the input the result is always incorrect. Could someone point me in the right direction as I don't have any experience with PHP.

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

  1. create_captcha(1, 20) - 3 + 7 = 10
  2. 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 this 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; ?>'>