How to Add and Validate CAPTCHA in PHP

by Lovepreet 4 minute read 6 views

Adding CAPTCHA to forms greatly boosts security, cuts back on spam entries, confirms users are human, and helps keep data clean and accurate across all submissions.

Key Points

  • CAPTCHA helps block up to 99% of automated spam in online contact and feedback forms.
  • Over 75% of websites depend on CAPTCHA to verify genuine user interaction online.
  • Forms with CAPTCHA see up to 90% fewer bot-driven submissions and fake entries.

Preventing spam and automated bot submissions is an important step in creating secure and professional websites. One of the most common and effective solutions is CAPTCHA — a simple test used to tell human users apart from bots.

This thorough tutorial explains how to add and validate CAPTCHA in PHP using a tidy folder structure, reusable components, and straightforward logic. Whether you're a freelance developer or a web development agency, this guide will assist you in securely integrating CAPTCHA into any form.

Folder Structure Overview

To ensure clarity and scalability, we’ll adopt a modular directory structure. This is particularly helpful for teams providing custom website development or handling projects within a web development firm.

                                        /project-folder/
├── index.php              # Contact form with CAPTCHA
├── captcha_image.php      # Dynamically generates CAPTCHA image
├── Model/
│   ├── Captcha.php        # CAPTCHA logic (generation, validation)
│   └── Contact.php        # Contact form DB logic (can be simulated)
                                    

Step 1: HTML Form (Add CAPTCHA Image + Subject & Message Fields)

This form features fields for user input, a dynamically generated CAPTCHA image, and an input box for entering the CAPTCHA code.

                                        <?php session_start(); ?>
<html>
<head>
    <title>PHP Captcha</title>
</head>
<body>
<h2>Contact Form with PHP Captcha</h2>

<form name="frmContact" method="post" action="">
    <table border="0" cellpadding="10" cellspacing="1" width="100%">
        <tr>
            <td>Name<br />
                <input type="text" name="userName" required>
            </td>
            <td>Email<br />
                <input type="email" name="userEmail" required>
            </td>
        </tr>
        <tr>
            <td colspan="2">Subject<br />
                <input type="text" name="subject" required>
            </td>
        </tr>
        <tr>
            <td colspan="2">Message<br />
                <textarea name="content" rows="5" required></textarea>
            </td>
        </tr>
        <tr>
            <td>
                Captcha Code:<br>
                <img src="captcha_image.php" alt="CAPTCHA"><br><br>
                <input name="captcha_code" type="text" required>
                <span style="color:red;"><?php if (isset($error_message)) echo $error_message; ?></span>
            </td>
            <td>
                <br>
                <input type="submit" name="submit" value="Submit">
            </td>
        </tr>
    </table>

    <?php if(isset($success_message)) { ?>
        <div style="color:green;"><?php echo $success_message; ?></div>
    <?php } ?>
</form>

</body>
</html>
                                    

Generating CAPTCHA Image (captcha_image.php)

The CAPTCHA code is generated and stored in the session. Then, a straightforward image is created using PHP’s GD library.

                                        <?php
require_once "./Model/Captcha.php";
use Phppot\Captcha;
session_start();
$captcha = new Captcha();
$code = $captcha->getCaptchaCode(6);
$captcha->setSession('captcha_code', $code);
$image = $captcha->createCaptchaImage($code);
$captcha->renderCaptchaImage($image);
?>
                                    

Creating the CAPTCHA Class (Model/Captcha.php)

This class manages CAPTCHA creation, image rendering, and validation. Such reusable classes are vital for scalable web development services.

                                        <?php
namespace Phppot;

class Captcha
{
    function __construct() {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    	}
   }

    function getCaptchaCode($length) //creates a 6 digit token
    {
        $random_alpha = md5(random_bytes(64));
        $captcha_code = substr($random_alpha, 0, $length);
        return $captcha_code;
    }

    function setSession($key, $value)
    {
        $_SESSION["$key"] = $value;
    }

    function getSession($key)
    {
        @session_start();
        $value = '';
        if (!empty($key) && !empty($_SESSION["$key"])) {
            $value = $_SESSION["$key"];
        }
        return $value;
    }

    function createCaptchaImage($captcha_code)
    {
        $target_layer = imagecreatetruecolor(72, 28);
        $captcha_background = imagecolorallocate($target_layer, 204, 204, 204);
        imagefill($target_layer, 0, 0, $captcha_background);
        $captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
        imagestring($target_layer, 5, 10, 5, $captcha_code, $captcha_text_color);
        return $target_layer;
    }

    function renderCaptchaImage($imageData)
    {
        header('Content-type: image/jpeg');
        imagejpeg($imageData);
    }

    function validateCaptcha($formData)
    {
        $isValid = false;
        $capchaSessionData = $this->getSession('captcha_code');

        if ($capchaSessionData == $formData) {
            $isValid = true;
        }
        return $isValid;
    }
}
?>
                                    

Handling Form Submission and CAPTCHA Validation

Add this PHP code to the top of your index.php file to validate form submission and the CAPTCHA input.

                                        <?php
require_once './Model/Captcha.php';
require_once './Model/Contact.php';

use Phppot\Captcha;
use Phppot\Contact;

session_start();

$captcha = new Captcha();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $userCaptcha = trim($_POST['captcha_code']);
    $isValidCaptcha = $captcha->validateCaptcha($userCaptcha);

    if ($isValidCaptcha) {
        $userName  = filter_var($_POST['userName'], FILTER_SANITIZE_STRING);
        $userEmail = filter_var($_POST['userEmail'], FILTER_SANITIZE_EMAIL);
        $subject   = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
        $content   = filter_var($_POST['content'], FILTER_SANITIZE_STRING);

        $contact = new Contact();
        $insertId = $contact->addToContacts($userName, $userEmail, $subject, $content);

        if (!empty($insertId)) {
            $success_message = 'Your message was received successfully.';
        }
    } else {
        $error_message = 'Incorrect Captcha Code.';
    }
}
?>
                                    

Why CAPTCHA Matters for Your Website

Whether you're offering web development services or building a product for a client, integrating CAPTCHA brings real benefits:

  • Blocks automated spam bots
  • Enhances website security
  • Improves data quality from contact forms
  • Protects against brute-force form abuse

As a professional web development company, adding features like CAPTCHA not only enhances your projects but also builds client trust in your development process.

Final Words

Implementing CAPTCHA is an essential skill for any developer focused on custom website development. It not only enhances security but also improves form validation quality. The modular approach explained here keeps your code maintainable, scalable, and easy to integrate with real databases.

This system can further be extended with:

  • CAPTCHA refresh button (AJAX-based)
  • Font styling
  • Noise or distortion for stronger protection

Want help adding those features or building a secure PHP system? Reach out to our team of experts — we specialize in delivering top-notch web development services.

Tech Stack & Version

Frontend

  • HTML5
  • CSS3
  • JavaScript

Backend

  • PHP
  • MySQL

Deployment

  • DigitalOcean
  • AWS
  • Linode
img

©2025Digittrix Infotech Private Limited , All rights reserved.