CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a simple security mechanism used to prevent automated bots from submitting forms on your website. While there are third-party CAPTCHA services like Google reCAPTCHA, creating a basic number-based CAPTCHA using PHP can be an effective and lightweight solution for small projects.
In this article, we’ll walk you through the process of creating a simple addition-based CAPTCHA using PHP sessions and form handling.
Why Use a Simple CAPTCHA?
Bots can easily submit forms, spam your website, or overload your server. A simple CAPTCHA that asks the user to solve a basic math problem (like 3 + 7) ensures that a human is interacting with your site.
Step-by-Step Guide
1. Start a Session and Generate Random Numbers
To create a dynamic math problem, we’ll generate two random numbers between 1 and 10 using PHP. We’ll store the correct answer in the session to compare it when the user submits the form.
<?php session_start(); $num1 = rand(1, 10); $num2 = rand(1, 10); $_SESSION['captcha_answer'] = $num1 + $num2; ?>
2. Create the Form with the CAPTCHA
Now, let’s build a simple HTML form that displays the math question and takes the user’s input.
<!DOCTYPE html> <html> <head> <title>Simple CAPTCHA Form</title> </head> <body> <h2>Contact Form with CAPTCHA</h2> <form action="submit.php" method="post"> Name: <input type="text" name="name" required><br><br> Email: <input type="email" name="email" required><br><br> What is <?php echo $num1; ?> + <?php echo $num2; ?>? <input type="text" name="captcha" required><br><br> <input type="submit" value="Submit"> </form> </body> </html>
This form asks the user a simple math question like “What is 3 + 5?” and takes the answer as input.
3. Validate the CAPTCHA on Form Submission
On the submit.php file, we validate the user’s answer by comparing it with the stored value in the session.
<?php
session_start();
$name = $_POST['name'];
$email = $_POST['email'];
$user_answer = $_POST['captcha'];
if ($user_answer == $_SESSION['captcha_answer']) {
echo "✅ Hello, $name. Your form was submitted successfully!";
// You can proceed to save the data or send an email
} else {
echo "❌ CAPTCHA failed. Please go back and try again.";
}
?>
If the answer matches the expected result, the form is considered valid.
Advantages of This Approach
-
No external dependencies – no need to integrate third-party services.
-
Lightweight and fast – simple math validation.
-
Effective for basic protection – ideal for small websites, blogs, or internal tools.
