Protecting Forms Using a CAPTCHA in PHP: A Complete Guide

Last updated 2 weeks, 4 days ago | 35 views 75     5

Tags:- PHP CAPTCHA

One of the most common security challenges in web development is preventing bots and spam from abusing your forms. CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a powerful solution that ensures the user filling out your form is human.

In this article, you'll learn:

  • Why CAPTCHA is important

  • How to implement a simple CAPTCHA in PHP

  • How to validate it

  • Code examples

  • Tips and common pitfalls


Why Use CAPTCHA?

CAPTCHAs help prevent:

  • Spam submissions on contact or registration forms

  • Automated account creation

  • Brute-force login attempts

  • Wasting server resources


Step-by-Step: Building a Basic PHP CAPTCHA

We’ll create a simple math-based CAPTCHA (e.g., "What is 5 + 3?") for this example.


Folder Structure

/captcha-form/
├── index.php         <-- Form with CAPTCHA
├── captcha.php       <-- CAPTCHA image generator
└── process.php       <-- Handles form submission

1️⃣ Generate CAPTCHA Image – captcha.php

<?php
session_start();

// Generate a random math problem
$num1 = rand(1, 9);
$num2 = rand(1, 9);
$_SESSION['captcha_answer'] = $num1 + $num2;

// Create image
header("Content-type: image/png");
$image = imagecreate(100, 30);

// Set colors
$bg_color = imagecolorallocate($image, 255, 255, 255); // white
$text_color = imagecolorallocate($image, 0, 0, 0); // black

// Add text to image
imagestring($image, 5, 10, 8, "$num1 + $num2 =", $text_color);

// Output image
imagepng($image);
imagedestroy($image);
?>

2️⃣ HTML Form with CAPTCHA – index.php

<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Form with CAPTCHA</title>
</head>
<body>
  <h2>Contact Us</h2>
  <form action="process.php" method="post">
    <label>Name:</label><br>
    <input type="text" name="name" required><br><br>

    <label>Message:</label><br>
    <textarea name="message" required></textarea><br><br>

    <label>CAPTCHA:</label><br>
    <img src="captcha.php" alt="CAPTCHA"><br>
    <input type="text" name="captcha" required><br><br>

    <input type="submit" value="Submit">
  </form>
</body>
</html>

3️⃣ Validate CAPTCHA and Process Form – process.php

<?php
session_start();

// Sanitize input
$name = trim($_POST['name'] ?? '');
$message = trim($_POST['message'] ?? '');
$captcha_input = trim($_POST['captcha'] ?? '');

// Validate CAPTCHA
if (!isset($_SESSION['captcha_answer']) || $captcha_input != $_SESSION['captcha_answer']) {
    echo "<p style='color:red;'>Incorrect CAPTCHA. Please go back and try again.</p>";
    exit;
}

// Reset CAPTCHA to prevent reuse
unset($_SESSION['captcha_answer']);

// Process form (this example just shows the input)
echo "<h3>Form Submitted Successfully!</h3>";
echo "<p><strong>Name:</strong> " . htmlspecialchars($name) . "</p>";
echo "<p><strong>Message:</strong> " . nl2br(htmlspecialchars($message)) . "</p>";
?>

✅ What Happens Behind the Scenes

  1. captcha.php creates a math CAPTCHA image and stores the correct answer in the session.

  2. index.php displays the form and CAPTCHA image.

  3. process.php validates the user’s answer and processes the form only if the answer is correct.


Tips for Better Security

  • ✅ Always regenerate the CAPTCHA on every new form load

  • ✅ Store CAPTCHA answers in $_SESSION and unset after checking

  • ✅ Sanitize all input fields

  • ✅ Use stronger CAPTCHA like Google reCAPTCHA v2/v3 for production websites

  • ✅ Combine with rate-limiting or honeypot fields for added protection


⚠️ Common Pitfalls to Avoid

Pitfall Explanation
CAPTCHA answer is reused Always unset the session variable after checking it
CAPTCHA image not loading Ensure captcha.php sends the correct Content-Type and no extra whitespace
CAPTCHA not secure Simple CAPTCHAs are easy to solve by bots. Consider third-party CAPTCHA like Google reCAPTCHA
Session not started Use session_start() at the top of each PHP file using $_SESSION
No image support Check if GD library is enabled in PHP (use phpinfo() to confirm)

Final Thoughts

Using CAPTCHA is one of the most effective ways to prevent automated abuse of your forms. A simple math CAPTCHA, like in this tutorial, is good for small projects or internal tools. For production-grade websites, integrating Google reCAPTCHA or hCaptcha provides better security and user experience.


Would you like a follow-up article on integrating Google reCAPTCHA v2 into your PHP form? Click here