Simple PHP Captcha for HTML Contact Forms

Posted on March 23, 2015 by Dan Doicaru in PHP Category

In this tutorial you will learn how to create a simple php captcha code for contact forms using PHP and some math operations to increase the security of your html form and reduce spam emails from users or bots.

We will generate two random numbers and sum them together, then user must do the math and write the answer in a text field. He will be redirected to another page where the sum of the two random numbers is calculated and compared with his answer. If the sum is correct, form will be submitted, but if the sum is wrong it will output an error message.

Full HD Video Tutorial

Preparing the Files

For this tutorial we will need 2 php files. One will contain the form with the simple php captcha and one will contain the code to validate what user has typed in the captcha field.

Preparing Files For Simple Php Captcha

Create Variables with Random Numbers for Our Simple PHP Captcha

First of all we will need to create 2 variables, one with a minimum number and one with a maximum number. Then you will need another 2 variables that will generate random numbers between the range of the minimum and maximum numbers created earlier. Below is the PHP code:

	$min_number = 1;
	$max_number = 15;

	$random_number1 = mt_rand($min_number, $max_number);
	$random_number2 = mt_rand($min_number, $max_number);

Display Generated Numbers to Users

Now that we have our numbers we need to echo (display) them to our users, so they can resolve the simple php captcha code. Also you will need to add a simple text input, giving a name attribute to retrieve inside a variable what user has typed in.

	echo $random_number1 . ' + ' . $random_number2 . ' = ';
<input name="captchaResult" type="text" />

After the user will fill the results, he will click the submit, then he will be redirected to another php file where we will validate the simple php captcha. To do that we will need to create 2 hidden inputs on the initial page, each field with his generated number.

<input name="firstNumber" type="hidden" value="<?php echo $random_number1; ?>" />
<input name="secondNumber" type="hidden" value="<?php echo $random_number2; ?>" />

Hidden inputs are not visible in page and can be used in php to store data inside variables, same as a regular text input. You can read more about input's type attribute here, including hidden attribute.

In the end, the code above must be added inside a <form> tag to process data, using the POST method, to send values inside text fields to the validation page when user will submit the results.

Simple PHP Captcha Demo

<form action="validateCaptcha.php" method="POST">
		Resolve the simple php captcha below: <br>
			echo $random_number1 . ' + ' . $random_number2 . ' = ';
		<input name="captchaResult" type="text" size="2" />

		<input name="firstNumber" type="hidden" value="<?php echo $random_number1; ?>" />
		<input name="secondNumber" type="hidden" value="<?php echo $random_number2; ?>" />

		<input type="submit" value="submit" />

Validating Captcha in Another File

In another file we will validate the value of the captcha field. If the sum of the 2 numbers will be the same as the number typed in by the user, will return true to the condition used. You can read more about if statements here.

To get the 2 random generated numbers together with the value of our captcha field, we will use $_POST variables. These will retrieve the values from the fields, stored by HTTP POST method used in our form.

	$captchaResult = $_POST["captchaResult"];
	$firstNumber = $_POST["firstNumber"];
	$secondNumber = $_POST["secondNumber"];

Great! Now that we have the numbers, we must sum the 2 numbers and check if the total match with the captcha number. To do that we will need another variables which will sum the random numbers. Check the code below:

$checkTotal = $firstNumber + $secondNumber;

if ($captchaResult == $checkTotal) {
	// captcha is OK
} else {
	// wrong captcha


This technique is great if you have a page where users can contact you through a contact form. Beside the email verification, is not that bad to have a simple php captcha that generates random numbers, without any images generated or other fancy things, just simple numbers. You will reduce significantly the spam you will receive on your email.

If you want a longer range of numbers, just change the max number to 100 or even bigger. You can download files or check the live demo below. I recommend you to read this tutorial about reducing comment spam almost to zero if you are using WordPress.

Live Demo

Download Files

Rate & Share
1 Star2 Stars3 Stars4 Stars5 Stars (6 votes, average: 3.83 out of 5)
Related Articles
  1. Gravatar Icon Vladimir:

    Good article. Many thanks. But I do not understand how to apply this lesson in the form of comments WordPress. Tell me please.

    • Hello Vladimir,

      This tutorial is intended to be used in html forms. In WordPress there is another story and another code. You can search for simple plugins specially developed for WordPress, that uses only math captcha.

  2. Gravatar Icon Mike:

    Good tutorial!

    I was searching for such math captcha and finally found this one. Almost fits my needs just would prefer to have the output into an image instead hidden input fields. Is that possible?

    I think its more secure … I’ve got a script for text captcha which works fine but I prefer math because of its simplicity. Unfortunately I’m a php rookie ;-) Maybe you can combine yours with mine?

    Caputure Image File looks like this:

    $img = imagecreatetruecolor(100,34);  // dimensions width height
    // text colors
    $white = imagecolorallocate($img, 255, 255, 255);
    $black = imagecolorallocate($img, 0, 0, 0);
    $grey = imagecolorallocate($img, 200, 200, 200);
    $highlight = imagecolorallocate($img, 67, 187, 180);
    function randomString($length) {
    	$chars = "abcdefghijklmnopqrstuvwxyz023456789";
    	$str = "";
    	$i = 0;
    	while ($i <= $length) {
    		$num = rand() % 33;
    		$tmp = substr($chars, $num, 1);
    		$str = $str . $tmp;
    	return $str;
    // Lines through captcha
        $color = (rand(1,2) == 1) ? $black : $grey;
        imageline($img,rand(5,70),rand(5,20), rand(5,70)+5,rand(5,20)+5, $color);
    	imageline($img,rand(5,70),rand(5,20), rand(5,70)+5,rand(5,20)+5, $color);
    imagefill($img, 0, 0, $white);
    $string = randomString(rand(5,7));
    $_SESSION['string'] = $string;
    imagettftext($img, 14, 0, 5, 22, $highlight, "fonts/calibri.ttf", $string);
    header("Content-type: image/png");
    and the form looks like this:
    <form action="#" method="post">
                            <label for="name">Name</label><br>
                            <input tabindex="1" type="text" id="name" name="name" placeholder="Name">
                            <label for="company">Company</label><br>
                            <input tabindex="2" type="text" id="company" name="company" placeholder="Company">
                            <label for="email">E-Mail</label><br>
                            <input tabindex="3" type="text" id="email" name="email" placeholder="E-Mail">
                            <label for="message">Nachricht</label><br>
                            <textarea tabindex="4" cols="20" rows="10" id="message" name="message" placeholder="Message"></textarea>
                        	<img src="capimg.php" alt="Capture" class="capimg">
                            <input class="captxt" type="text" id="image" name="image" placeholder="Captcha eingeben">                        
                        <div class="clearfix"></div>
                            <input tabindex="5" type="submit" value="Nachricht senden" class="submit">                            
                        <?php if($error == true) { ?>
                        <p class="error">Please fill out all required fields</p>
                        <?php } if($sent == true) { ?>
                        <p class="gesendet">We've got your message. We'll answer as soon as possible!</p>
                        <?php } ?>
Hint: Wrap your code syntax (html, css or others) between <pre> and </pre> tags. All comments are moderated.

6 + = 13

Subscribe by E-mail

HTML-TUTS is created and maintained by Dan Doicaru.
This website is a rebrand to Extreme Design Studio (, built under WordPress platform.