CAPTCHA in PHP Forms
In this lesson: Add a simple math/image CAPTCHA to PHP forms with sessions, plus when to use Google reCAPTCHA — full code. Stop bots now.
Why forms need a CAPTCHA
Automated bots can flood your forms with fake signups, spam comments and junk messages. A CAPTCHA is a small challenge that a human can pass easily but a bot cannot — like solving a simple sum. Adding one keeps your forms clean without much effort.
A simple math CAPTCHA
<?php
session_start();
$a = random_int(1, 9);
$b = random_int(1, 9);
$_SESSION["captcha"] = $a + $b; // store the answer
echo "What is $a + $b?"; // show the question
?>
We pick two random numbers, store their sum in the session, and display the question. The user sees only the question, never the answer.
Store the answer safely
Notice the answer went into $_SESSION — server-side. This is important: if you put the answer in a hidden field or cookie, a bot could just read it. Keeping it in the session means only your PHP knows the correct value.
Verify the answer
<?php
session_start();
$answer = $_POST["captcha"] ?? "";
if ($answer == ($_SESSION["captcha"] ?? null)) {
echo "CAPTCHA passed - likely human";
// continue processing the form
} else {
echo "Wrong answer - try again";
}
?>
Compare the submitted answer to the stored one. On a match, treat it as a human and process the form; otherwise, reject and ask again.
When to use reCAPTCHA
A simple math CAPTCHA is great for learning and low-traffic forms. But determined bots can sometimes beat it. For important public forms — signups, contact pages on busy sites — use Google reCAPTCHA, which is far harder for bots and often invisible to real users.
Common mistakes
- Storing the answer client-side. A hidden field or cookie can be read by bots — use the session.
- Using
rand()for the numbers. Preferrandom_intfor less predictable challenges. - Relying on CAPTCHA alone. Still validate input and use prepared statements.
- Making it too hard. A CAPTCHA that frustrates real users hurts more than it helps.
Summary
- A CAPTCHA blocks bots with a challenge easy for humans.
- Generate a simple question and store the answer in the session.
- Show only the question; keep the answer server-side.
- Compare the user's answer to the stored one to verify.
- Use Google reCAPTCHA for important, high-traffic public forms.
Next, validate the rest of the form with form validation, or secure it with XSS prevention.
