Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 50

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.

💡 The idea: show a challenge, keep the correct answer on the server, and compare the user's answer to it.

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
?>
What is 3 + 4?

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";
  }
?>
CAPTCHA passed - likely human

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. Prefer random_int for 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.

Frequently Asked Questions

What is a CAPTCHA and why use one?
A CAPTCHA is a small challenge — like a math sum or distorted text — that is easy for humans but hard for bots. It stops automated scripts from spamming your forms with fake signups, comments or messages.
How does a simple PHP CAPTCHA work?
You generate a challenge (say 3 + 4), store the correct answer in the session, and show the question. When the form is submitted, you compare the user's answer to the stored one. A match means a likely human.
Where should I store the CAPTCHA answer?
In the session, server-side. Never put the answer in a hidden field or cookie, because a bot could read it. Only the question is shown; the answer stays on the server.
When should I use Google reCAPTCHA instead?
For real production sites facing serious bot traffic, Google reCAPTCHA is stronger than a simple math CAPTCHA. A homemade CAPTCHA is fine for learning and low-risk forms, but reCAPTCHA is the robust choice for important public forms.
Does a CAPTCHA replace input validation?
No. A CAPTCHA reduces bots, but you still validate and sanitize all input, and use prepared statements. Think of CAPTCHA as one layer among several, not a complete security solution.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Course complete! Continue withE-commerce App (Android + PHP) Your progress: 50 / 50 (100%) · Recommended next course Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free